package net.dgg.rz.production.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.DggValidateUtil;
import net.dgg.framework.tac.utils.exception.DggBaseException;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.ScGeneralService;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.iboss.base.util.*;
import net.dgg.rz.api.production.service.ApiProductionService;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.*;
import net.dgg.rz.common.dao.AllotRecordDao;
import net.dgg.rz.common.entity.AllotRecord;
import net.dgg.rz.common.entity.CustomerRecord;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.service.CommonService;
import net.dgg.rz.common.systemRecord.dao.SystemRecordDao;
import net.dgg.rz.common.systemRecord.entity.SystemRecord;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.*;
import net.dgg.rz.customer.vo.AfterSaleChangeStatusMessageVo;
import net.dgg.rz.customer.vo.AfterSaleChangeStatusProductItemVo;
import net.dgg.rz.customer.vo.AfterSaleProductHandleItemVo;
import net.dgg.rz.customer.vo.AfterSaleProductHandleMessageVo;
import net.dgg.rz.production.dao.*;
import net.dgg.rz.production.entity.*;
import net.dgg.rz.production.entity.dto.OrderBusJsonDto;
import net.dgg.rz.production.entity.dto.ProductOrderDto;
import net.dgg.rz.production.exception.FlowNodeExcption;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.rz.production.utils.ParamsBuildUtils;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationEntity;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.role.service.RoleService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 生产订单
 * Created by zyou on 2018/12/17.
 */
@Service
public class ProductOrderService extends BaseService {

    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private ProductNodeFlowDao productNodeFlowDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private SystemRecordDao systemRecordDao;
    @Autowired
    private DesUtil desUtil;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SearchUtils searchUtils;
    @Autowired
    private DataPermissionUtils dataPermissionUtils;
    @Autowired
    private ScGeneralService scGeneralService;
    //查询协办人service
    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private OrganizationManager organizationManager;
    //用户service
    @Autowired
    private UserService userservice;
    @Autowired
    private FlowNodeService flowNodeService;
    @Autowired
    AllotRecordDao allotRecordDao;
    @Autowired
    private ProductTimeStatusService productTimeStatusService;
    @Autowired
    private OrderContactDao orderContactDao;
    @Autowired
    private OrderCustomerDao orderCustomerDao;
    @Autowired
    private UniqueOrderUtils uniqueOrderUtils;
    @Autowired
    private ParamsBuildUtils paramsBuildUtils;
    @Autowired
    private OrderJsonDao orderJsonDao;
    @Autowired
    private ProductNodeService productNodeService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ApiProductionService apiProductionService;

    @Resource
    private TreeBookService treeBookService;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 分页查询生产订单列表数据
     */
    @Transactional
    public List<ProductOrderDto> scOrderWithPage(Map params) {
        return productOrderDao.scOrderWithPage(params);
    }

    /**
     * PC 待处理 分页查询生产订单列表数据
     */
    @Transactional
    public List<ProductOrderDto> processingscOrderWithPage(Map params) {
        List<ProductOrderDto> productOrderDtos = new ArrayList<>();
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        List<String> statusAttr = new ArrayList<>();
//        params.put("orderDir", "desc");
//        params.put("orderColumn", "t.update_time");

        String target = String.valueOf(params.get("target"));

        switch (target) {
            case "0":
                //数据权限参数注入
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                //待接收页面
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && statusAttr.contains(params.get("statusAttr"))) {
                    statusAttr.clear();
                    statusAttr.add(String.valueOf(params.get("statusAttr")));
                }
                params.put("statusArr", statusAttr);

                break;
            case "1":
                //办理中页面(办理中取出已放款数据)
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS02);
                params.put("statusArr", statusAttr);
                params.put("isLoan", "0");//0表示未放款的
                //数据权限参数注入
                dataPermissionUtils.inProcessDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "2":
                //已暂缓页面
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS03);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "3"://废单
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS08);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                break;
            case "4"://放款
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS02);
                params.put("statusArr", statusAttr);
                params.put("isLoan", "1");
                dataPermissionUtils.inProcessDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "5"://退单
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS06);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                break;
            case "6"://退单驳回
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS09);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "7"://废单驳回
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS10);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "8"://全部
                if ("2".equals(params.get("userLocked"))) {
                    //说明是异常订单
                    dataPermissionUtils.productOrgDataAccess(params, ModuleCodeConstant.RZSC_ABNORMALORDER_CODE);
                } else {
                    dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_ALLORDER_CODE);
                }
                /*params.put("statusArr", statusAttr);*/
                break;
            case "9"://已完结
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS17);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS19);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            default:
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && statusAttr.contains(params.get("statusAttr"))) {
                    statusAttr.clear();
                    statusAttr.add(String.valueOf(params.get("statusAttr")));
                } else if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && !statusAttr.contains(params.get("statusAttr"))) {
                    return productOrderDtos;
                }
                params.put("statusArr", statusAttr);
                //数据权限参数注入
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
        }


        //入参操作
        searchUtils.paramsOperate(params);
        productOrderDtos = productOrderDao.scOrderWithPage(params);
        //翻译字段
        String[] transColum = {"originCode", "status", "suspendReason","afterSaleStatus","productHandleResultType"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }

    /**
     * APP 待处理 分页查询生产订单列表数据
     */
    @Transactional
    public List<ProductOrderDto> findProductOrderWithPage(Map<String, Object> params) {
        ValidateUtils.strNotEmpty(params.get("userLoginName"), ProductOrderExcption.class, "未获取到登陆人，请重新登录");
        List<ProductOrderDto> productOrderDtos = new ArrayList<>();
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        List<String> statusAttr = new ArrayList<>();
        String target = params.get("target").toString();

        switch (target) {
            case "0":
                //数据权限参数注入
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                //待接收页面
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && statusAttr.contains(params.get("statusAttr"))) {
                    statusAttr.clear();
                    statusAttr.add(String.valueOf(params.get("statusAttr")));
                }
                params.put("statusArr", statusAttr);

                break;
            case "1":
                //办理中页面(办理中取出已放款数据)
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS02);
                params.put("statusArr", statusAttr);
                params.put("isLoan", "0");//0表示未放款的
                //数据权限参数注入
                dataPermissionUtils.inProcessDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "2":
                //已暂缓页面
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS03);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "3"://废单
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS08);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                break;
            case "4"://放款
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS02);
                params.put("statusArr", statusAttr);
                params.put("isLoan", "1");
                dataPermissionUtils.inProcessDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "5"://退单
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS06);
                params.put("statusArr", statusAttr);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                break;
            case "6"://退单驳回
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS09);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "7"://废单驳回
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS10);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "8"://全部
                if ("2".equals(params.get("userLocked"))) {
                    //说明是异常订单
                    dataPermissionUtils.productOrgDataAccess(params, ModuleCodeConstant.RZSC_ABNORMALORDER_CODE);
                } else {
                    dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_ALLORDER_CODE);
                }
                /*params.put("statusArr", statusAttr);*/
                break;
            case "9"://已完结
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS17);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS19);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "10":
                //办理中页面(所有办理中页面)
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS02);
                params.put("statusArr", statusAttr);
                //数据权限参数注入
                dataPermissionUtils.inProcessDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
            case "11"://下单待接收
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "12"://转单待接收
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                params.put("statusArr", statusAttr);
                break;
            case "13"://退回待接收
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                params.put("statusArr", statusAttr);
                break;


            default:
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && statusAttr.contains(params.get("statusAttr"))) {
                    statusAttr.clear();
                    statusAttr.add(String.valueOf(params.get("statusAttr")));
                } else if (StringUtils.isNotEmpty(String.valueOf(params.get("statusAttr"))) && !statusAttr.contains(params.get("statusAttr"))) {
                    return productOrderDtos;
                }
                params.put("statusArr", statusAttr);
                //数据权限参数注入
                dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_PROCESSING_CODE);
                break;
        }


        //入参操作
        searchUtils.paramsOperateApp(params);
        productOrderDtos = productOrderDao.findProductOrderWithPage(params);
        //翻译字段
        String[] transColum = {"originCode", "suspendReason", "status","rateTypeName"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);

        for (ProductOrderDto productOrderDto: productOrderDtos) {
            productOrderDto.setWayOfLoanName(ModuleCodeConstant.paymentMethod.get(productOrderDto.getWayOfLoan()));
        }
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }

    /**
     * 待分配 分页查询生产订单列表数据
     */
    @Transactional
    public List<ProductOrderDto> waitAllocateOrderWithPage(Map params) {
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        List<String> statusAttr = new ArrayList<>();

        statusAttr.add(ScProductConstant.RZSCORDER_STATUS14);
        params.put("statusArr", statusAttr);

        //数据权限参数注入
        dataPermissionUtils.productOrgDataAccess(params, ModuleCodeConstant.RZSC_ALLOTORDER_CODE);
        //入参操作
        searchUtils.paramsOperate(params);
        List<ProductOrderDto> productOrderDtos = productOrderDao.scOrderWithPage(params);
        //翻译字段
        String[] transColum = {"originCode", "status"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);

        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }


    /**
     * 待审核 分页查询生产订单列表数据
     */
    @Transactional
    public List<ProductOrderDto> auditOrderWithPage(Map params) {
        List<String> statusAttr = new ArrayList<>();

        String target = String.valueOf(params.get("target"));
        switch (target) {
            case "0":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS05);
                params.put("statusArr", statusAttr);
                break;
            case "1":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS07);
                params.put("statusArr", statusAttr);
                break;
            case "2":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS22);
                params.put("statusArr", statusAttr);
                break;
            default:
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS05);
                params.put("statusArr", statusAttr);
                break;
        }


        //数据权限参数注入
        dataPermissionUtils.auditorDataAccess(params);
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "当前未登录，请登录后重试");
        params.put("flowUser", userEntity.getId());
        //入参操作
        searchUtils.paramsOperate(params);
        List<ProductOrderDto> productOrderDtos = productOrderDao.scOrderForAuditWithPage(params);

        //翻译字段
        String[] transColum = {"originCode", "status"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 事业部订单分页数据
     * @Date 18:26 2019/1/10
     * @Param
     **/
    @Transactional
    public List<ProductOrderDto> busDepOrderWithPage(Map params) {
        List<String> statusAttr = new ArrayList<>();
        params.put("orderDir", "desc");
        params.put("orderColumn", "t.update_time");
        params.put("statusArr", statusAttr);

        //数据权限参数注入
        dataPermissionUtils.productOrgDataAccess(params, ModuleCodeConstant.RZSC_BUSDEPORDER_CODE);
        //入参操作
        searchUtils.paramsOperate(params);
        List<ProductOrderDto> productOrderDtos = productOrderDao.scOrderWithPage(params);
        //翻译字段
        String[] transColum = {"originCode", "status"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }

    /**
     * 接收订单(单个)
     *
     * @param
     * @param
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void singleReceiveOrder(JSONObject params) throws IOException {
        this.productChangeParams(params, ScProductConstant.RZSC_ORIGINCODE_AACCEPT_CHANGE);
        Long scOrderId = params.getLong("id");
        String typeCode = params.getString("typeCode");
        Long productId = params.getLong("productId");
        //Long goodsId = params.getLong("goodsId");
        Long channelId = params.getLong("channelId");
        //支行
        String channelSubBranch = params.getString("channelSubBranch");

        //现有生产订单
        ProductOrder oldScOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        ValidateUtils.strNotEmpty(oldScOrder, ProductOrderExcption.class, "未查询到该生产订单的信息！");

        List<String> statusList = new ArrayList<>();
        statusList.add(ScProductConstant.RZSCORDER_STATUS01);
        statusList.add(ScProductConstant.RZSCORDER_STATUS11);
        statusList.add(ScProductConstant.RZSCORDER_STATUS16);

        ValidateUtils.isTrue(statusList.contains(oldScOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态已改变，请刷新列表！");
        UserEntity userEntity = searchUtils.getcurrUser(params);
        //当前登录用户所属部门信息
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.isTrue(userEntity.getId().equals(oldScOrder.getFlowUserId()), ProductOrderExcption.class, "您不是所选生产订单的流程人员，不能进行该操作！");

        //没有更换产品，只更新订单状态
        if (oldScOrder.getBusinessProductCode().equals(typeCode)
                && oldScOrder.getProductId().equals(productId)
                && null != oldScOrder.getChannelId()
                && oldScOrder.getChannelId().equals(channelId)) {
            //获取当前登录用户
            Date now = new Date();
            //查询业务类型
            Map busTypeMap = cmsService.getTreeBookObj(typeCode);
            ValidateUtils.strNotEmpty(busTypeMap, ProductOrderExcption.class, "未查询到业务类型信息");
            //通过流程id查询流程并将节点更新为第一个节点
            ProductNodeFlow productNodeFlow = null;
            List<ProductNode> productNode = new ArrayList<ProductNode>();
            Long serialId = commonService.getSerialId(productId);
            if(StringUtils.isNotEmpty(oldScOrder.getNodeJson())){
                Map maps = new HashMap<>();
                maps.put("productId", serialId);
                maps.put("businessTypeCode", oldScOrder.getBusinessTypeCode());//一级业态Code
                maps.put("smallBusinessTypeCode", oldScOrder.getBusinessProductCode());// 二级业态Code
                productNodeFlow =  apiProductionService.getNodeFlow(maps);
                productNode = JSONArray.parseArray(oldScOrder.getNodeJson(), ProductNode.class);
            }else{
                Map nodeFlowIdMap = new HashMap();
                Long productNodeFlowId = productNodeFlowDao.selectFlowIdByProIdAndBusCode(typeCode, serialId);
                nodeFlowIdMap.put("flowId", productNodeFlowId);
                nodeFlowIdMap.put("version", oldScOrder.getVersion());
                productNodeFlow = productNodeFlowDao.selectFlowById(nodeFlowIdMap);
                Integer old = productNodeFlow.getIsOld();
                if (old==null||old.equals(0)) {
                    productNode = flowNodeService.queryByFlowId(nodeFlowIdMap);
                }else {
                    productNode= flowNodeService.queryByFlowIdAndVersion(nodeFlowIdMap);
                }
            }

            ValidateUtils.strNotEmpty(productNodeFlow, CommonExcption.class, "当前流程不存在！");
            ValidateUtils.isTrue(productNode.size() > 0, CommonExcption.class, "当前流程节点不存在！");
            //更新记录id
            Long operatingId = DggKeyWorker.nextId();
            //节点更新记录表实体
            ProductNodeOperating operating = new ProductNodeOperating();
            operating.setId(operatingId);
            operating.setScProductOrderId(oldScOrder.getId());
            operating.setScProductOrderNo(oldScOrder.getScProductOrderNo());
            operating.setFlowUserId(userEntity.getId());
            operating.setFlowUserName(userEntity.getRealName() + userEntity.getLoginName());
            operating.setFlowOrgId(userEntity.getOrgId());
            operating.setFlowOrgName(org.getName());
            operating.setOrderStatus(oldScOrder.getStatus());
            operating.setNodeId(productNode.get(0).getId());
            operating.setNodeName(productNode.get(0).getName());
            operating.setNodeProcessTime(productNode.get(0).getHandleDate());
            operating.setNodeProcessTimeType(productNode.get(0).getIsNaturalorWorkday().toString());
            operating.setRemarksType(1);
            operating.setRemark(userEntity.getRealName() + userEntity.getLoginName() + "接收订单");
            //节点流程表实体
            ValidateUtils.strNotEmpty(productNodeFlow, ProductOrderExcption.class, "未查询到对应流程配置");
            operating.setNodeProcessTimeType(productNodeFlow.getIsnaturalorworkday() == null ? null : productNodeFlow.getIsnaturalorworkday().toString());
            operating.setNodeOpetateTime(now);
            operating.setCreateUser(userEntity);
            operating.setCreateTime(now);
            operating.setCreaterOrgName(org.getName());
            //超期计算
            ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(oldScOrder.getId());
            if (timestatus == null) {
                timestatus = productTimeStatusService.insertProductStatus(oldScOrder);
            }
            if (null != timestatus && null != timestatus.getReceiveEndTime()) {
                int i = DateUtils.compare_date(new Date(), timestatus.getReceiveEndTime());
                if (i >= 1) {
                    timestatus.setReceiveTimeStatus(ScProductConstant.TIME_OUT);
                    operating.setNodeStartTime(timestatus.getReceiveStartTime());
                    operating.setNodeEndTime(timestatus.getReceiveEndTime());
                    operating.setNodeTimeStatus(ScProductConstant.TIME_OUT);
                    String date = DateUtils.transTime(timestatus.getReceiveEndTime(), new Date());
                    operating.setNodeOverdueTime(date);
                    //接收节点扣罚
                    flowNodeService.nodePunish(operating, oldScOrder, productNode.get(0));
                } else {
                    timestatus.setReceiveTimeStatus(timestatus.getReceiveTimeStatus());
                    operating.setNodeStartTime(timestatus.getReceiveStartTime());
                    operating.setNodeEndTime(timestatus.getReceiveEndTime());
                    operating.setNodeTimeStatus(ScProductConstant.NORMAL);
                }
                //默认的下一节点计划更新时间
                timestatus.setNodeStartTime(now);
                Date currentDate = commonService.getDateFromStartByType(now,
                        productNode.get(1).getHandleDate(), 0L,
                        productNode.get(1).getIsNaturalorWorkday());//节点截止时间计算
                timestatus.setNodeEndTime(currentDate);
                timestatus.setNodeId(productNode.get(1).getId());
                timestatus.setNodeName(productNode.get(1).getName());
                timestatus.setNodeProcessTime(productNode.get(1).getHandleDate());
                timestatus.setNodeProcessTimeType(productNode.get(1).getIsNaturalorWorkday());
                timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
                productTimeStatusDao.updateByPrimaryKeySelective(timestatus);
            }
            productNodeOperatingDao.insertSelective(operating);

            ProductOrder productOrder = new ProductOrder();
            productOrder.setId(oldScOrder.getId());
            productOrder.setReceiverId(userEntity.getId());// 接收人
            productOrder.setReceiverName(userEntity.getRealName() + userEntity.getLoginName());// 接收人
            productOrder.setReceiverOrgId(userEntity.getOrgId());// 接收人部门
            productOrder.setReceiverOrgName(org.getName());// 接收人部门名称
            productOrder.setReceiveTime(now);// 流程人员接收时间
            productOrder.setReceiveOrderDate(now);//接单时间
            productOrder.setFlowUserId(userEntity.getId());// 流程人员Id
            productOrder.setFlowUserName(userEntity.getRealName() + userEntity.getLoginName());// 流程人员Id
            productOrder.setFlowUserOrgId(userEntity.getOrgId());// 流程人员部门Id
            productOrder.setFlowUserOrgName(org.getName());// 流程人员部门name
            productOrder.setSubBranch(channelSubBranch);
            productOrder.setUpdaterUser(userEntity);
            productOrder.setUpdaterOrgName(org.getName());
            productOrder.setUpdateTime(now);

            productOrder.setLatestEndUserId(userEntity.getId());
            productOrder.setLatestEndUserName(userEntity.getRealName() + userEntity.getLoginName());
            productOrder.setLatestEndNodeId(productNode.get(0).getId());
            productOrder.setLatestEndNodeName(productNode.get(0).getName());
            productOrder.setLatestEndNodeTime(now);
            productOrder.setLatestNodeOperatingId(operatingId);
            productOrder.setLatestFlowOperatingId(oldScOrder.getNodeFlowId());
            productOrder.setLatestEndUserOrgId(userEntity.getOrgId());
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS02);// 变成办理中
            productOrderDao.updateByPrimaryKeySelective(productOrder);
            if(0 == oldScOrder.getIsJdSms()){
                Map contentParamMap = new HashMap();
                contentParamMap.put("orderNo",oldScOrder.getOrderNo());
                TreeBook treeBook = null;
                try{
                    treeBook = treeBookService.getTreeBookByCode("RZSC_MESSAGE_TEMPLATE_JD");
                }catch (Exception e){
                    logger.error("查询短信模板id数据字典失败：",e.toString());
                }
                Map resultMap = commonService.sendSMS(desUtil.decrypt(oldScOrder.getCustomerPhone()), net.dgg.rz.common.utils.StringUtils.isNotEmpty(treeBook)?treeBook.getExt1():"", contentParamMap, "接单触发", 1);
                if(10000 == Long.valueOf(resultMap.get("code").toString())){
                    productOrderDao.updateSendSms(oldScOrder.getOrderNo());
                }else {
                    logger.error(resultMap.toString());
                }
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE3);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent("接收订单");
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
        } else {//如果更换了产品的信息，则需要走更新产品的步骤
            this.changeProduct(params, ScProductConstant.RZSC_ORIGINCODE_AACCEPT_CHANGE);
        }

    }


    /**
     * 接收订单(批量)
     *
     * @param
     * @return
     */
    @Transactional
    @SuppressWarnings("all")
    public void receiveOrder(String orderIds,String userLoginName) {
        UserEntity user = searchUtils.getcurrUser(new HashMap(){{
            put("userLoginName", userLoginName);
        }});// 当前操作人
        Map map = this.commonMangerExtService.findOrg(user.getOrgId());
        JSONArray jsonObject = JSON.parseArray(orderIds);
        List<Long> scProductOrderIdList = new ArrayList<>();
        for (Object id : jsonObject) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(user, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map, ProductOrderExcption.class, "未获取到登陆人部门信息，请重新登录！");
        for (ProductOrder scProOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到生产订单，请刷新列表！");
            List<String> statusList = new ArrayList<>();
            statusList.add(ScProductConstant.RZSCORDER_STATUS01);
            statusList.add(ScProductConstant.RZSCORDER_STATUS11);
            statusList.add(ScProductConstant.RZSCORDER_STATUS16);
            ValidateUtils.isTrue(statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态已改变，请刷新列表！");
        }
        Date date = new Date();
        List<Long> orderIdList = new ArrayList<>();
        for (ProductOrder order : scProOrderList) {
            ValidateUtils.isTrue(user.getId().equals(order.getFlowUserId()), ProductOrderExcption.class, "无权操作,当前操作人不是接收人");
            ValidateUtils.strNotEmpty(order.getNodeFlowId(), ProductOrderExcption.class, "未查询到" + order.getProductOrgName() + "流程节点配置信息");

            ProductNodeFlow productNodeFlow = null;
            List<ProductNode> productNode = new ArrayList<ProductNode>();
            Long serialId = commonService.getSerialId(order.getProductId());
            if(StringUtils.isNotEmpty(order.getNodeJson())){
                Map maps = new HashMap<>();
                maps.put("productId", serialId);
                maps.put("businessTypeCode", order.getBusinessTypeCode());//一级业态Code
                maps.put("smallBusinessTypeCode", order.getBusinessProductCode());// 二级业态Code
                productNodeFlow =  apiProductionService.getNodeFlow(maps);
                productNode = JSONArray.parseArray(order.getNodeJson(), ProductNode.class);
            }else{
                Map nodeFlowIdMap = new HashMap();
                nodeFlowIdMap.put("flowId", order.getNodeFlowId());
                nodeFlowIdMap.put("version", order.getVersion());
                productNodeFlow = productNodeFlowDao.selectFlowById(nodeFlowIdMap);
                Integer old = productNodeFlow.getIsOld();
                if (old==null||old.equals(0)) {
                    productNode = flowNodeService.queryByFlowId(nodeFlowIdMap);
                }else {
                    productNode= flowNodeService.queryByFlowIdAndVersion(nodeFlowIdMap);
                }
            }
            ValidateUtils.strNotEmpty(productNode, ProductOrderExcption.class, "未查询到" + order.getProductOrgName() + "流程节点配置信息");
            ValidateUtils.isTrue(productNode.size() > 0, ProductOrderExcption.class, "未查询到" + order.getProductOrgName() + "流程节点配置信息");
            orderIdList.add(order.getId());
            order.setReceiverId(user.getId());// 接收人
            order.setReceiverName(user.getRealName() + user.getLoginName());// 接收人
            order.setReceiverOrgId(user.getOrgId());// 接收人部门
            order.setReceiverOrgName(map.get("name").toString());// 接收人部门名称
            order.setReceiveTime(date);// 流程人员接收时间
            order.setReceiveOrderDate(date);//接单时间
            order.setFlowUserId(user.getId());// 流程人员Id
            order.setFlowUserName(user.getRealName() + user.getLoginName());// 流程人员Id
            order.setFlowUserOrgId(user.getOrgId());// 流程人员Id
            order.setFlowUserOrgName(map.get("name").toString());// 流程人员name
            order.setUpdaterUser(user);
            order.setUpdaterOrgName(map.get("name").toString());
            order.setUpdateTime(date);

            Long operatingId = DggKeyWorker.nextId();//更新记录id
            order.setLatestEndUserId(user.getId());
            order.setLatestEndUserName(user.getRealName() + user.getLoginName());
            order.setLatestEndNodeId(productNode.get(0).getId());
            order.setLatestEndNodeName(productNode.get(0).getName());
            order.setLatestEndNodeTime(date);
            order.setLatestNodeOperatingId(operatingId);
            order.setLatestFlowOperatingId(order.getNodeFlowId());
            order.setLatestEndUserOrgId(user.getOrgId());
            order.setStatus(ScProductConstant.RZSCORDER_STATUS02);// 变成办理中
            productOrderDao.updateByPrimaryKeySelective(order);
            //节点更新记录表实体
            ProductNodeOperating operating = new ProductNodeOperating();
            operating.setId(operatingId);
            operating.setScProductOrderId(order.getId());
            operating.setScProductOrderNo(order.getScProductOrderNo());
            operating.setFlowUserId(user.getId());
            operating.setFlowUserName(user.getRealName());
            operating.setFlowOrgId(user.getOrgId());
            operating.setFlowOrgName(map.get("name").toString());
            operating.setOrderStatus(order.getStatus());
            operating.setNodeId(productNode.get(0).getId());
            operating.setNodeName(productNode.get(0).getName());

            operating.setNodeProcessTime(productNode.get(0).getHandleDate());
            operating.setNodeProcessTimeType(productNode.get(0).getIsNaturalorWorkday().toString());
            operating.setRemarksType(1);
            operating.setRemark(user.getRealName() + user.getLoginName() + "接收订单");
            //节点流程表实体
            operating.setNodeProcessTimeType(productNodeFlow.getIsnaturalorworkday() == null ? null : productNodeFlow.getIsnaturalorworkday().toString());
            operating.setNodeOpetateTime(new Date());
            operating.setCreateUser(user);
            operating.setCreateTime(new Date());
            operating.setCreaterOrgName(map.get("name").toString());
            //超期计算
            ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
            if (timestatus == null) {
                timestatus = productTimeStatusService.insertProductStatus(order);
            }
            if (null != timestatus && null != timestatus.getReceiveEndTime()) {
                int i = DateUtils.compare_date(new Date(), timestatus.getReceiveEndTime());
                if (i >= 1) {
                    timestatus.setReceiveTimeStatus(timestatus.getReceiveTimeStatus());
                    operating.setNodeTimeStatus(ScProductConstant.TIME_OUT);
                    String overDate = DateUtils.transTime(timestatus.getReceiveEndTime(), new Date());
                    operating.setNodeOverdueTime(overDate);
                    //接收节点扣罚
                    flowNodeService.nodePunish(operating, order, productNode.get(0));
                } else {
                    timestatus.setReceiveTimeStatus(timestatus.getReceiveTimeStatus());
                    operating.setNodeTimeStatus(ScProductConstant.NORMAL);
                }
                operating.setNodeStartTime(timestatus.getReceiveStartTime());
                operating.setNodeEndTime(timestatus.getReceiveEndTime());
                //默认的下一节点计划更新时间
                timestatus.setNodeStartTime(date);
                Date currentDate = commonService.getDateFromStartByType(date,
                        productNode.get(1).getHandleDate(), 0L,
                        productNode.get(1).getIsNaturalorWorkday());//节点截止时间计算
                timestatus.setNodeEndTime(currentDate);
                timestatus.setNodeId(productNode.get(1).getId());
                timestatus.setNodeName(productNode.get(1).getName());
                timestatus.setNodeProcessTime(productNode.get(1).getHandleDate());
                timestatus.setNodeProcessTimeType(productNode.get(1).getIsNaturalorWorkday());
                timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
                productTimeStatusDao.updateByPrimaryKeySelective(timestatus);
            }
            productNodeOperatingDao.insertSelective(operating);
            if(0 == order.getIsJdSms()){
                Map contentParamMap = new HashMap();
                contentParamMap.put("orderNo",order.getOrderNo());
                TreeBook treeBook = null;
                try{
                    treeBook = treeBookService.getTreeBookByCode("RZSC_MESSAGE_TEMPLATE_JD");
                }catch (Exception e){
                    logger.error("查询短信模板id数据字典失败：",e.toString());
                }
                Map resultMap = commonService.sendSMS(desUtil.decrypt(order.getCustomerPhone()), net.dgg.rz.common.utils.StringUtils.isNotEmpty(treeBook)?treeBook.getExt1():"", contentParamMap, "接单触发", 1);
                if(10000 == Long.valueOf(resultMap.get("code").toString())){
                    productOrderDao.updateSendSms(order.getOrderNo());
                }else {
                    logger.error(resultMap.toString());
                }
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(order.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(order.getId());
            customerRecord.setTableNo(order.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE3);
            customerRecord.setCreaterId(user.getId());
            customerRecord.setContent("接收订单");
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(order,null,user);
        }
    }


    //----------------------------------------------------zyou-------------------------------------------------------------------

    /**
     * 新增渠道
     *
     * @param params
     */
    @Transactional
    @SuppressWarnings("all")
    public void addChannel(Map params) {
        //验证页面传递参数
        DggValidateUtil.notNull(params, ProductOrderExcption.class, "参数为空！");
        DggValidateUtil.notNull(params.get("id"), ProductOrderExcption.class, "生产订单id为空！");
        DggValidateUtil.notNull(params.get("channelId"), ProductOrderExcption.class, "渠道id为空！");
        DggValidateUtil.notNull(params.get("channelName"), ProductOrderExcption.class, "渠道name为空！");
        DggValidateUtil.notNull(params.get("processUserId"), ProductOrderExcption.class, "流程人员id为空！");
        DggValidateUtil.notNull(params.get("contractNo"), ProductOrderExcption.class, "合同编号为空！");
        DggValidateUtil.notNull(params.get("amount"), ProductOrderExcption.class, "金额为空！");


        //获取当前登录用户
        UserEntity userEntity = sessionManager.getCurrentUser();
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        Map curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());

        //通过生产订单id查询生产订单基础信息
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.parseLong(params.get("id").toString()));
        DggValidateUtil.notNull(productOrder, ProductOrderExcption.class, "没有找到该生产订单！");

        boolean res = uniqueOrderUtils.uniqueOrder((JSONObject) JSON.toJSON(params), productOrder.getOrderId(), SystemCommonConstant.PRODUCT_ADD);
        if (res) {
            ValidateUtils.isTrue(!res, CommonExcption.class, "商品+渠道不唯一，请核查后再试");
        }
        //不是办理中的不能新增渠道
        ValidateUtils.isTrue(ScProductConstant.RZSCORDER_STATUS02.equals(productOrder.getStatus()), ProductOrderExcption.class, "当前生产订单不在办理中，不能新增渠道");
        ValidateUtils.isTrue(productOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "您不是流程人员，不能进行该操作！");

        //验证流程人员是否存在
        Map processUser = cmsService.findUser(Long.parseLong(params.get("processUserId").toString()));
        ValidateUtils.strNotEmpty(processUser, ProductOrderExcption.class, "当前流程人员不存在！");

        //转换页面传递参数
        Long processUserId = Long.parseLong(params.get("processUserId").toString());//流程人员id
        String processRealLoginName = processUser.get("realName").toString() + processUser.get("loginName").toString();//流程人员名称和登录名
        Long processOrgId = processUser.get("orgId") == null ? null : Long.parseLong(processUser.get("orgId").toString());
        String processOrgName = processUser.get("orgName") == null ? "" : processUser.get("orgName").toString();//流程人员所属事业部名称

        //获取生产子订单编号
        String number = cmsService.getBillNumber("sc");
        ValidateUtils.strNotEmpty(number, ProductOrderExcption.class, "单据号获取失败,请联系管理员！");

        //新增
        ProductOrder addProductOrder = new ProductOrder();
        Date now = new Date();
        long newId = DggKeyWorker.nextId();
        addProductOrder.setId(newId);//主订单id
        this.saveOpt(addProductOrder, userEntity);//保存通用参数
        addProductOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        addProductOrder.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        addProductOrder.setScProductOrderNo(number);//产子订单编号
        addProductOrder.setOrderId(productOrder.getOrderId());//销售主订单ID
        addProductOrder.setOrderNo(productOrder.getOrderNo());//销售主订单编号
        addProductOrder.setOrderBusId(productOrder.getOrderBusId());//销售子订单ID
        addProductOrder.setOrderBusNo(productOrder.getOrderBusNo());//售子订单编号
        addProductOrder.setBusinessId(productOrder.getBusinessId());//商机ID
        addProductOrder.setBusinessNo(productOrder.getBusinessNo());//商机编号
        addProductOrder.setCustomerId(productOrder.getCustomerId());//客户ID
        addProductOrder.setCustomerNo(productOrder.getCustomerNo());//客户编号
        addProductOrder.setCustomerPhone(productOrder.getCustomerPhone());//客户电话
        addProductOrder.setCustomerName(productOrder.getCustomerName());//客户名称
        addProductOrder.setContactPhone(productOrder.getContactPhone());//联系人电话
        addProductOrder.setProductOrgId(productOrder.getProductOrgId());//生产所属ID
        addProductOrder.setProductOrgName(productOrder.getProductOrgName());//生产所属名字
        addProductOrder.setBusinessTypeCode(productOrder.getBusinessTypeCode());//业态标识code
        addProductOrder.setBusinessTypeName(productOrder.getBusinessTypeName());//业态名字
        addProductOrder.setBusinessProductCode(productOrder.getBusinessProductCode());//小业态产品code
        addProductOrder.setBusinessProductName(productOrder.getBusinessProductName());//小业态产品名字
        addProductOrder.setProductId(productOrder.getProductId()); //产品ID
        addProductOrder.setProductName(productOrder.getProductName()); //产品名字
        addProductOrder.setChannelId(Long.parseLong(params.get("channelId").toString())); //渠道ID
        addProductOrder.setChannelName(params.get("channelName").toString()); //渠道名称
        addProductOrder.setSubBranch(params.get("subBranch") == null ? "" : params.get("subBranch").toString()); //支行
        addProductOrder.setContractNo(params.get("contractNo").toString()); //合同编号
        addProductOrder.setOrderTime(productOrder.getOrderTime());   //签单时间
        addProductOrder.setReceiveTime(now);   //流程人员接收时间
        addProductOrder.setLoanAmount(new BigDecimal(params.get("amount").toString()));
        addProductOrder.setAllotWay(productOrder.getAllotWay());  //分配方式
        addProductOrder.setMoney(productOrder.getMoney());
        addProductOrder.setAllotDate(productOrder.getAllotDate()); //分配时间
        addProductOrder.setOriginCode(productOrder.getOriginCode());  //订单来源(来源方式)
        addProductOrder.setServiceCharge(productOrder.getServiceCharge());
        addProductOrder.setRateType(productOrder.getRateType());
        //接收人改为选择流程人员的部门及当前时间
        addProductOrder.setReceiverId(processUserId);  //接单人id
        addProductOrder.setReceiverName(processRealLoginName);  //接单人名字
        addProductOrder.setReceiverOrgId(processOrgId);  //接单人部门ID
        addProductOrder.setReceiverOrgName(processOrgName); //接单人部门
        addProductOrder.setReceiveOrderDate(new Date()); //接单时间
        addProductOrder.setPayMethod(productOrder.getPayMethod()); //付款方式
        addProductOrder.setSignUserId(productOrder.getSignUserId());  //签单商务ID
        addProductOrder.setSignUserName(productOrder.getSignUserName()); //签单商务名字
        addProductOrder.setSignUserOrgId(productOrder.getSignUserOrgId());    //签单商务部门ID
        addProductOrder.setSignUserOrgName(productOrder.getSignUserOrgName());   //签单商务部门名字
        addProductOrder.setSignOrgId(productOrder.getSignOrgId());  //签单事业部ID
        addProductOrder.setSignOrgName(productOrder.getSignOrgName()); //签单事业部名字
        addProductOrder.setSignTime(productOrder.getSignTime());
        addProductOrder.setFlowUserId(processUserId);  //流程人员ID
        addProductOrder.setFlowUserName(processRealLoginName);   //流程人员名字
        addProductOrder.setFlowUserOrgId(processOrgId);   //流程人员部门ID
        addProductOrder.setFlowUserOrgName(processOrgName); //流程人员部门名字
        addProductOrder.setNodeFlowId(productOrder.getNodeFlowId()); //节点流程id
        addProductOrder.setStatus(ScProductConstant.RZSCORDER_STATUS02);//办理中
        addProductOrder.setRemark(productOrder.getRemark());  //备注

        // 更新流程的自定义字段，不进行保存

        //通过流程id查询流程并将节点更新为第一个节点
        Map nodeFlowIdMap = new HashMap();
        ProductNodeFlow productNodeFlow = null;
        ProductNode productNode = null;
        if(StringUtils.isNotEmpty(addProductOrder.getNodeJson())){
            Map maps = new HashMap<>();
            maps.put("productId", productOrder.getProductId());
            maps.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            maps.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            productNodeFlow =  apiProductionService.getNodeFlow(maps);
            List<ProductNode> productNodes = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
            if(!CollectionUtils.isEmpty(productNodes)){
                for(ProductNode p :productNodes){
                    if("接单".equals(p.getName())){
                        productNode = p;
                    }
                }
            }
        }else{
            nodeFlowIdMap.put("flowId", productOrder.getNodeFlowId());
            productNodeFlow = productNodeFlowDao.queryFlowById(nodeFlowIdMap);
            productNode = productNodeDao.queryNodeJd(nodeFlowIdMap);//流程节点
        }
        ValidateUtils.strNotEmpty(productNodeFlow, CommonExcption.class, "当前流程不存在！");
        ValidateUtils.strNotEmpty(productNode, CommonExcption.class, "当前流程节点不存在！");

        addProductOrder.setLatestEndUserId(processUserId); //最新节点更新人ID
        addProductOrder.setLatestEndUserName(processRealLoginName);  //最新节点更新人名字
        addProductOrder.setLatestEndUserOrgId(processOrgId);  //最新节点更新人部门ID
        addProductOrder.setLatestEndNodeId(productNode.getId());  //最新完成节点ID
        addProductOrder.setLatestEndNodeName(productNode.getName());//最新完成节点名字
        addProductOrder.setLatestEndNodeTime(now);//最新完成节点时间
        Long nodeOperatingId = DggKeyWorker.nextId();
        addProductOrder.setLatestNodeOperatingId(nodeOperatingId);  //当前节点操作记录ID
        addProductOrder.setLatestFlowOperatingId(productOrder.getNodeFlowId()); //当前流程操作记录ID

        addProductOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_PRO_ADD); //订单来源

        //保存新增渠道主订单
        productOrderDao.insertSelective(addProductOrder);

        //新增流程记录
        ProductNodeOperating productNodeOperating = new ProductNodeOperating();
        productNodeOperating.setId(nodeOperatingId);//流程记录表id
        productNodeOperating.setScProductOrderId(addProductOrder.getId());  //生产子订单ID
        productNodeOperating.setScProductOrderNo(addProductOrder.getOrderNo());  //生产子订单编号
        productNodeOperating.setFlowUserId(processUserId);   //流程人员id
        productNodeOperating.setFlowUserName(processRealLoginName); //流程人员名字
        productNodeOperating.setFlowOrgId(processOrgId);   //流程人员部门id
        productNodeOperating.setFlowOrgName(processOrgName);   //流程人员部门名字
        productNodeOperating.setOrderStatus(addProductOrder.getStatus());  //生产订单状态
        productNodeOperating.setNodeId(productNode.getId()); //节点ID
        productNodeOperating.setNodeName(productNode.getName());   //节点名称
        productNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL);   //节点超期状态
        productNodeOperating.setNodeProcessTimeType(productNodeFlow.getIsnaturalorworkday() == null ? null : productNodeFlow.getIsnaturalorworkday().toString());  //节点办理时长类型
        productNodeOperating.setNodeStartTime(now);   //节点开始时间
        productNodeOperating.setNodeEndTime(now);  //节点截至时间
        productNodeOperating.setNodeOpetateTime(now);  //节点完成时间
        productNodeOperating.setCreaterOrgName(processOrgName);
        productNodeOperating.setRemark(productNode.getName());
        this.saveOpt(productNodeOperating, userEntity);//设置基础字段
        productNodeOperatingDao.insert(productNodeOperating);

        //插入操作记录
        SystemRecord record = new SystemRecord();
        record.setId(DggKeyWorker.nextId());
        record.setSource("2");
        record.setWorkTableName("rzsc_product_order");
        record.setWorkId(addProductOrder.getId());
        record.setWorkNo(addProductOrder.getScProductOrderNo());
        record.setSignOrgId(addProductOrder.getSignOrgId());
        record.setSignOrgName(addProductOrder.getSignOrgName());
        record.setWorkNo(addProductOrder.getScProductOrderNo());
        record.setBeOperaterId(userEntity.getId());
        record.setOperateType("40");
        record.setRemarks("新增渠道");
        record.setOperaterId(userEntity.getOrgId());//操作人员id
        record.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());//操作人员名称
        record.setOperateTime(new Date());//操作时间
        if (org != null) {
            record.setOperaterOrgId(org.getId());
            record.setOperaterOrgName(org.getName());
        } else {
            throw new ProductOrderExcption("未获取到登录用户所在部门信息");
        }
        systemRecordDao.insert(record);
        //插入生产订单超期
        ProductTimeStatus timestatus = new ProductTimeStatus();
        timestatus.setId(addProductOrder.getId());//超期表id和新增主订单id一样
        timestatus.setScProductOrderNo(addProductOrder.getScProductOrderNo());//  //生产子订单编号
        timestatus.setReceiveStartTime(now);  //接收计时开始时间
        timestatus.setReceiveProcessTime(0);  //接收时长
        timestatus.setReceiveEndTime(now);   //接收截至时间
        timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);  //接收超期状态
        timestatus.setNodeFlowId(addProductOrder.getNodeFlowId());  //节点流程ID
        timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);  //节点超期状态
        timestatus.setDistributionStartTime(now);    //分配开始时间

        timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);   //订单超期状态
        timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL); //分配超期状态
        timestatus.setFlag(1);//必须要加入

        if (productNodeFlow.getIsnaturalorworkday() == 1) {//工作日
            Date nowDate = new Date();
            String orderEndTime = cmsService.findAfterDate(DateUtil.dateToString(nowDate, "yyyy-MM-dd HH:mm:ss"), productNodeFlow.getManagementCycle()) + " " + DateUtil.dateToString(nowDate, "HH:mm:ss");
            timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime, "yyyy-MM-dd HH:mm:ss"));
        } else {
            try {
                timestatus.setOrderEndTime(DateUtils.dateAddDayJs(now, productNodeFlow.getManagementCycle()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        timestatus.setOrderStartTime(now);
        timestatus.setOrderProcessTime(productNodeFlow.getManagementCycle());
        timestatus.setOrderProcessTimeType(productNodeFlow.getIsnaturalorworkday());
        this.saveOpt(timestatus, userEntity);//设置基础字段

        productTimeStatusDao.insertSelective(timestatus);


    }

    /**
     * 订单转单
     *
     * @return
     */
    @Transactional
    public Map<String, String> transferOrder(String orderIds, Long transferUserId, String transferOrderRemark, String userLoginName) {
        ValidateUtils.strNotEmpty(orderIds, CommonExcption.class, "订单id不能为空");
        ValidateUtils.strNotEmpty(transferUserId, CommonExcption.class, "转单人不能为空");
        ValidateUtils.strNotEmpty(transferOrderRemark, ProductOrderExcption.class, "备注为空，请填写备注");
        ValidateUtils.isTrue(transferOrderRemark.length()<=500, ProductOrderExcption.class, "备注内容不能超过500，请核查后再提交");
        String[] ids = orderIds.split(",");
        Map<String, String> result = new HashMap<>();
        result.put("flag", "0");
        if (ids == null || ids.length < 1) {
            result.put("msg", "订单id不能为空");
            return result;
        }
        Date newDate = new Date();
        UserEntity userEntity = searchUtils.getcurrUser(new HashMap() {{
            put("userLoginName", userLoginName);
        }});// 当前操作人
        for (String idStr : ids) {
            Long id = Long.parseLong(idStr);
            ProductOrder order = productOrderDao.selectByPrimaryKey(id);//当前订单
            result.put("orderBusNo", order.getScProductOrderNo());
            Long uId = null;//转单前流程人员id

            String uName = "";//转单前流程人员name

            Long deptId = null;//转单前流程人员部门id

            String deptName = "";//转单前流程人员部门
            if (userEntity.getId().equals(transferUserId)) {
                result.put("msg", "不能转给自己");
                return result;
            }
            if (!userEntity.getId().equals(order.getFlowUserId())) {
                result.put("msg", order.getScProductOrderNo() + "：没有该生产单的操作权限");
                return result;
            }
            //验证转单人部门是否属于当前登录人所属事业部
            UserEntity flower = userService.findUserById(transferUserId);

            Map busDep = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
            Map flowUserBusDep = commonMangerExtService.findBusDeptById(Long.valueOf(flower.getOrgId()));
            ValidateUtils.strNotEmpty(busDep, ProductOrderExcption.class, "未查询到当前登录人所属事业部");
            ValidateUtils.strNotEmpty(flowUserBusDep, ProductOrderExcption.class, "未查询到当前所选流程人员所属事业部");
            ValidateUtils.isTrue(Long.valueOf(String.valueOf(flowUserBusDep.get("id"))).equals(Long.valueOf(String.valueOf(busDep.get("id")))), ProductOrderExcption.class, "当前所选流程人员与当前登录人所属事业部不同，不能进行转单");

      /*      List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(userEntity.getOrgId());
            if(!childOrganizationList.contains(flower.getOrgId())){
                result.put("msg","转单人所属部门不在当前登录人部门下");
                return result;
            }*/
            if (!userEntity.getId().equals(order.getFlowUserId())) {
                result.put("msg", "您无权操作,当前操作人不是当前流程人员");
                return result;
            }

            /*if (order.getAllotWay().equals(ScProductConstant.ALLOT_TO_FLOW_USER)) {// 分配给生产人
                if (!userEntity.getId().equals(order.getReceiverId())) {
                    return "您无权操作,当前操作人不是接收人";
                }
                uId = order.getReceiverId();//接单人id
                uName = order.getReceiverName();//接单人
                deptId = order.getReceiverOrgId();
                deptName = order.getReceiverOrgName();
                order.setProductUserId(null);
                order.setProductUserName(null);
                order.setProductUserId(null);
                order.setProductOrgId(null);
            } else {
                if (!userEntity.getId().equals(order.getProductUserId())) {
                    return "您无权操作,当前操作人不是接收人";
                }
                uId = order.getProductUserId();//负责人id
                uName = order.getProductUserName();//负责人
                deptId = order.getProductOrgId();
                deptName = order.getProductOrgName();
                order.setReceiverId(null);
                order.setReceiverName(null);
                order.setReceiverOrgId(null);
                order.setReceiverOrgName(null);
            }*/
            if (!order.getStatus().equals(ScProductConstant.RZSCORDER_STATUS01)
                    && !order.getStatus().equals(ScProductConstant.RZSCORDER_STATUS11)
                    && !order.getStatus().equals(ScProductConstant.RZSCORDER_STATUS16)
                    && !ScProductConstant.RZSCORDER_STATUS02.equals(order.getStatus())
            ) {
                // 如果当前状态不是分配待接收、转单待接收、转交待接收、移交待接收、办理中
                result.put("msg", "当前订单状态已改变，不能进行转单");
                return result;
            }
            Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());//当前操作人部门
            /*UserEntity transfer = userService.findUserById(transferUserId);*/
            Map transfermap = this.commonMangerExtService.findOrg(flower.getOrgId());//接收人部门
            order.setStatus(ScProductConstant.RZSCORDER_STATUS11);//转单待接收
           /* order.setReceiverId(transfer.getId());
            order.setReceiverName(transfer.getRealName()+transfer.getLoginName());
            order.setReceiverOrgId(Long.parseLong(transfermap.get("id").toString()));
            order.setReceiverOrgName(transfermap.get("name").toString());*/
            //流程人员改了
            /*order.setFlowUserId(transfer.getId());// 流程人员Id
            order.setFlowUserName(transfer.getRealName()+transfer.getLoginName());// 流程人员Id
            order.setFlowUserOrgId(Long.parseLong(transfermap.get("id").toString()));// 流程人员Id
            order.setFlowUserOrgName(transfermap.get("name").toString());// 流程人员Id*/
            order.setUpdaterUser(userEntity);
            order.setUpdaterOrgName(map.get("name").toString());
            order.setUpdateTime(newDate);
            order.setFlowUserId(flower.getId());
            order.setFlowUserName(flower.getRealName() + flower.getLoginName());
            order.setFlowUserOrgName(transfermap.get("name").toString());
            order.setFlowUserOrgId(Long.parseLong(transfermap.get("id").toString()));
            order.setWaitingReceiverId(userEntity.getId());
            order.setWaitingReceiverName(userEntity.getRealName() + userEntity.getLoginName());
            order.setWaitingReceiverOrgId(userEntity.getOrgId());
            order.setWaitingReceiverOrgName(map.get("name").toString());
            order.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_SLIP);//资源来源----转单
            //最新备注时间
            order.setLastRemarkTime(newDate);
            order.setLastRemark(transferOrderRemark);
            productOrderDao.updateByPrimaryKeySelective(order);

            //超期计算
            ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
            if (timestatus == null) {
                timestatus = productTimeStatusService.insertProductStatus(order);
            } else {
                timestatus.setReceiveStartTime(newDate);
                timestatus.setReceiveProcessTime(1);
                try {
                    timestatus.setReceiveEndTime(DateUtils.dateAddDayJs(newDate, 1));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                productTimeStatusDao.updateByPrimaryKey(timestatus);
            }

            // 插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());// id
            record.setSource("2");
            record.setWorkTableName("rzsc_product_order");
            record.setWorkId(order.getId());
            record.setWorkNo(order.getScProductOrderNo());
            record.setOperateType("24");
            record.setRemarks("订单转单:" + transferOrderRemark);
            record.setBeOperaterId(flower.getId());
            record.setBeOperaterName(flower.getRealName() + flower.getLoginName());
            record.setBeOperaterOrgId(flower.getOrgId());
            record.setBeOperaterOrgName(String.valueOf(transfermap.get("name")));
            systemRecordService.save(record, flower, userEntity);
            try {// 发送消息 生产订单{0}已经于{1}转单给你，请及时确认处理！
                String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                List<UserEntity> users = new ArrayList<>();
                users.add(flower);//接收人
                commonService.sendMsgByAsynchronous(users, msgs, "RZSC_SC_SLIP");//转单模板
            } catch (Exception e) {
                e.printStackTrace();
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(order.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(order.getId());
            customerRecord.setTableNo(order.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE5);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent(transferOrderRemark);
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(order,null,userEntity);
        }
        result.put("flag", "1");
        result.put("msg", "转单成功");
        return result;
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 申请退单
     * @Date 16:13 2018/12/25
     * @Param
     **/
    @Transactional
    public void abandonReasonOrder(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(jsonObject.getString("ids"), ProductOrderExcption.class, "生产订单ID为空！");
        List<Long> scProductOrderIdList = new ArrayList<>();
        String idsStr = jsonObject.getString("ids");
//        ValidateUtils.isTrue(ids.size() <=10, ProductOrderExcption.class, "最多选择10条数据");
        JSONArray ids = JSONArray.parseArray(idsStr);
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退单的数据` ");
        Map userAuditor = cmsService.findUser(jsonObject.getLong("auditorId"));
        ValidateUtils.strNotEmpty(userAuditor, ProductOrderExcption.class, "未查询到选择的审核人，请重新选择审核人！");
        OrganizationEntity organizationEntity = organizationManager.findOrgEntityByOrgId(Long.parseLong(userAuditor.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未查询到选择的审核人，请从新选择审核人！");
       /* Map applyReason = commonMangerExtService.getTreeBookObj(jsonObject.getString("applyReasonCode"));
        ValidateUtils.strNotEmpty(applyReason, ProductOrderExcption.class, "未查询到选择的退单理由，请重新选择");*/
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(scProOrderList, ProductOrderExcption.class, "未查询生产订单，请刷新列表！");
        //获取本部门及所有下属部门ID
        List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(Long.parseLong(userAuditor.get("orgId").toString()));
        ValidateUtils.isTrue(childOrganizationList.contains(userEntity.getOrgId()), ProductOrderExcption.class, "审核人所属事业部没在当前登录人部门中");
        for (ProductOrder scProOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
            ValidateUtils.isTrue(userEntity.getId().equals(scProOrder.getFlowUserId()), ProductOrderExcption.class, "没有该生产单的操作权限");
            ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "退单原因为空，请描述退单原因");
            List<String> statusList = new ArrayList<>();
            statusList.add(ScProductConstant.RZSCORDER_STATUS05); //退单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS09);//退单驳回
            statusList.add(ScProductConstant.RZSCORDER_STATUS10);//废单驳回
            statusList.add(ScProductConstant.RZSCORDER_STATUS06);//已退单
//            statusList.add(ScProductConstant.RZSCORDER_STATUS11);//转单待接收
//            statusList.add(ScProductConstant.RZSCORDER_STATUS16);//退回待接收
            statusList.add(ScProductConstant.RZSCORDER_STATUS03);//暂缓
            statusList.add(ScProductConstant.RZSCORDER_STATUS07);//废单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS05);//退单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS19);//超期完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS17);//生产完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS20);//强制完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS08);//已废单
            ValidateUtils.isTrue(!statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态不能操作退单，请刷新列表！");
        }
//        ProductOrder scProOrder = this.productOrderDao.selectByPrimaryKey(jsonObject.getLong("id"));

        //调用IBOSS接口判断能否退单  打开注释即可(注释内是资质用接口）
  /*      try {
            orfApiService.isPossibleOrder(scProOrder.getOrderBusId());
        } catch (Exception e) {
            throw new ProductOrderExcption(e.getMessage());
        }*/

        List<ProductOrder> productOrders = new ArrayList<>();
        List<SystemRecord> systemRecords = new ArrayList<>();
        Date date = new Date();
        for (ProductOrder scProOrder : scProOrderList) {
            SystemRecord systemRecord = new SystemRecord();
            if (StringUtils.isNotEmpty(jsonObject.getString("remark"))) {
                scProOrder.setRemark(jsonObject.getString("remark"));
                systemRecord.setRemarks(jsonObject.getString("remark"));//备注记录
                //最新备注时间
                scProOrder.setLastRemarkTime(date);
                scProOrder.setLastRemark(jsonObject.getString("remark"));
            }
            scProOrder.setBeforeStatus(scProOrder.getStatus());//退单之前的状态
            scProOrder.setAuditorId(Long.parseLong(userAuditor.get("id").toString()));
            scProOrder.setAuditorName(userAuditor.get("realName").toString().concat(userAuditor.get("loginName").toString()));
            scProOrder.setBeforeStatus(scProOrder.getStatus());//获取发起申请订单的状态
            scProOrder.setAbandonReasonTime(date); //申请时间
            scProOrder.setAbandonReason(jsonObject.getString("applyReasonCode")); //申请类型
            scProOrder.setAbandonUserId(userEntity.getId()); //申请人ID
            scProOrder.setAbandonUser(userEntity.getRealName() + userEntity.getLoginName()); //申请人
            scProOrder.setStatus(ScProductConstant.RZSCORDER_STATUS05); //退单待审核
            scProOrder.setAbandonReasonNum(0);
            this.updateOpt(scProOrder, userEntity);
            productOrderDao.updateByPrimaryKeySelective(scProOrder);
//            productOrders.add(scProOrder);
            //记录
            systemRecord.setWorkId(scProOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            systemRecord.setOperateType("6");//操作类型 : 退单
            systemRecord.setSource("2");//来源生产
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(organizationEntity.getId());
            systemRecord.setOperaterOrgName(organizationEntity.getName());
            systemRecord.setOperateTime(date);
            systemRecords.add(systemRecord);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(scProOrder.getId());
            customerRecord.setTableNo(scProOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE8);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent(jsonObject.getString("remark"));
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(scProOrder,null,userEntity);
        }
        //批量更新订单状态
//        productOrderDao.updateBatchById(productOrders);
        //插入操作日志
        systemRecordService.saveRecords(systemRecords);

    }


    /**
     * @return
     * @Author cuipeng
     * @Description //TODO 转单退回
     * @Date 2019/1/10
     * @Param
     **/
    @Transactional
    public void backorderSave(String id, String remark, String userLoginName) {
        //验证是否有权限操作
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(Long.parseLong(id));
        //判断只有转单待接收的生产单才可以退回
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS11), ProductOrderExcption.class, "只有转单待接收状态的生产单才能退回");
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到对应的生产订单信息！");
        UserEntity userEntity = searchUtils.getcurrUser(new HashMap() {{
            put("userLoginName", userLoginName);
        }});
        Date now = new Date();
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.isTrue(productOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "您无权操作,当前操作人不是接收人！");

        ValidateUtils.isTrue(remark.length() <= 500, ProductOrderExcption.class, "备注信息不能超过500个字！");
        Map map = commonMangerExtService.findOrg(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(map, ProductOrderExcption.class, "接收失败,系统参数异常,请联系管理员！");
        Long uId = productOrder.getWaitingReceiverId();//退回前流程人员id
        String uName = productOrder.getWaitingReceiverName();//退回前流程人员name
        Long deptId = productOrder.getWaitingReceiverOrgId();//退回前流程人员部门id
        String deptName = productOrder.getWaitingReceiverOrgName();//退回前流程人员部门
        //int commonStatus = 2;//用于区分发送消息的模板
        UserEntity user = new UserEntity();
        ValidateUtils.strNotEmpty(uId, ProductOrderExcption.class, "退回失败,未查询到订单原流程人员！");
        user = userservice.findUserById(uId);
        ProductOrder backOrder = new ProductOrder();
        backOrder.setId(Long.parseLong(id));
        backOrder.setStatus(ScProductConstant.RZSCORDER_STATUS16);
        ValidateUtils.strNotEmpty(user, ProductOrderExcption.class, "退回失败,未查询到订单原流程人员信息！");
        backOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_SLIP_RETURN);
        /*backOrder.setReceiverId(user.getId());
        backOrder.setReceiverName(user.getRealName());
        backOrder.setReceiverOrgId(Long.parseLong(receicveMap.get("id")+""));
        backOrder.setReceiverOrgName(receicveMap.get("name")+"");*/
        //为了保证异常订单正常工作, 除开下单待分配的退回   退回的时候把流程人员写进去
        backOrder.setFlowUserId(uId);
        backOrder.setFlowUserName(uName);
        backOrder.setFlowUserOrgId(deptId);
        backOrder.setReceiverOrgName(deptName);
        /*backOrder.setWaitingReceiverId(null);
        backOrder.setWaitingReceiverName(null);
        backOrder.setWaitingReceiverOrgId(null);
        backOrder.setWaitingReceiverOrgName(null);*/
        backOrder.setUpdaterId(userEntity.getId());
        backOrder.setUpdaterName(userEntity.getRealName());
        backOrder.setUpdaterOrgId(userEntity.getOrgId());
        backOrder.setUpdaterOrgName(map.get("name") + "");
        backOrder.setUpdateTime(now);
        //最新备注时间
        if (StringUtils.isNotBlank(remark)) {
            backOrder.setLastRemark(remark);
            backOrder.setLastRemarkTime(now);
        }
        productOrderDao.updateByPrimaryKeySelective(backOrder);
        //超期计算
        ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(backOrder.getId());
        if (timestatus == null) {
            timestatus = productTimeStatusService.insertProductStatus(backOrder);
        } else {
            timestatus.setReceiveStartTime(now);
            timestatus.setReceiveProcessTime(1);
            try {
                timestatus.setReceiveEndTime(DateUtils.dateAddDayJs(now, 1));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            productTimeStatusDao.updateByPrimaryKey(timestatus);
        }
        // 插入操作记录
        SystemRecord record = new SystemRecord();
        record.setId(DggKeyWorker.nextId());// id
        record.setSource("2");
        record.setWorkTableName("rzsc_product_order");
        record.setWorkId(productOrder.getId());
        record.setWorkNo(productOrder.getScProductOrderNo());
        record.setOperateType("10");
        record.setRemarks("转单退回:" + remark);
        systemRecordService.save(record, user, userEntity);
        try {//退回发送消息 失败就算了
            //转单待接收的退回 转单的生产订单{0}已经于{1}被退回，请及时确认处理！
            String[] msgs = new String[]{productOrder.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
            List<UserEntity> users = new ArrayList<>();
            users.add(user);//接收人
            commonService.sendMsgByAsynchronous(users, msgs, "RZSC_SC_SLIP_GO_BACK");//转单退回模板
        } catch (Exception e) {
            e.printStackTrace();
        }
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(backOrder.getCustomerId());
        customerRecord.setTableName("rzsc_product_order");
        customerRecord.setTableId(backOrder.getId());
        customerRecord.setTableNo(backOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE12);
        customerRecord.setCreaterId(userEntity.getId());
        customerRecord.setContent(remark);
        MQMessageSendUtil.ucMessageSend(customerRecord);
        //同步生产单状态给企大宝
        MQMessageSendUtil.qdsMessageSend(backOrder,null,userEntity);
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 废单申请
     * @Date 18:57 2018/12/25
     * @Param
     **/
    @Transactional
    public void nullifyReasonOrder(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");

        Map userAuditor = cmsService.findUser(jsonObject.getLong("auditorId"));
        ValidateUtils.strNotEmpty(userAuditor, ProductOrderExcption.class, "未查询到选择的审核人，请重新选择审核人！");
        OrganizationEntity organizationEntity = organizationManager.findOrgEntityByOrgId(Long.parseLong(userAuditor.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未查询到选择的审核人，请从新选择审核人！");
        ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "退单原因为空，请描述退单原因");
        /*Map applyReason = commonMangerExtService.getTreeBookObj(jsonObject.getString("applyReasonCode"));
        ValidateUtils.strNotEmpty(applyReason, ProductOrderExcption.class, "未查询到选择的退单理由，请重新选择");*/

        List<Long> scProductOrderIdList = new ArrayList<>();
        String idsStr = jsonObject.getString("ids");
        JSONArray ids = JSONArray.parseArray(idsStr);
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
//        ValidateUtils.isTrue(ids.size() <= 10, ProductOrderExcption.class, "最多选择10条数据");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据` ");
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(scProOrderList, ProductOrderExcption.class, "未查询生产订单，请刷新列表！");
        //验证审核人是否是当前登录人所属事业部门的
        //获取本部门及所有下属部门ID
        List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(Long.parseLong(userAuditor.get("orgId").toString()));
        ValidateUtils.isTrue(childOrganizationList.contains(userEntity.getOrgId()), ProductOrderExcption.class, "审核人所属事业部没在当前登录人部门中");
        for (ProductOrder scProOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
            ValidateUtils.isTrue(userEntity.getId().equals(scProOrder.getFlowUserId()), ProductOrderExcption.class, "没有该生产单的操作权限");
            List<String> statusList = new ArrayList<>();
            statusList.add(ScProductConstant.RZSCORDER_STATUS05); //退单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS09);//退单驳回
            statusList.add(ScProductConstant.RZSCORDER_STATUS10);//废单驳回
            statusList.add(ScProductConstant.RZSCORDER_STATUS06);//已退单
//            statusList.add(ScProductConstant.RZSCORDER_STATUS11);//转单待接收
//            statusList.add(ScProductConstant.RZSCORDER_STATUS16);//退回待接收
            statusList.add(ScProductConstant.RZSCORDER_STATUS03);//暂缓
            statusList.add(ScProductConstant.RZSCORDER_STATUS07);//废单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS05);//退单待审核
            statusList.add(ScProductConstant.RZSCORDER_STATUS17);//生产完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS20);//强制完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS19);//超期完结
            statusList.add(ScProductConstant.RZSCORDER_STATUS08);//已废单
            ValidateUtils.isTrue(!statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态不能操作退单，请刷新列表！");
        }

        //调用IBOSS接口判断能否退单  打开注释即可(注释内是资质用接口）
  /*      try {
            orfApiService.isPossibleOrder(scProOrder.getOrderBusId());
        } catch (Exception e) {
            throw new ProductOrderExcption(e.getMessage());
        }*/
        List<ProductOrder> productOrders = new ArrayList<>();
        List<SystemRecord> systemRecords = new ArrayList<>();
        Date date = new Date();
        for (ProductOrder scProOrder : scProOrderList) {
            SystemRecord systemRecord = new SystemRecord();
            if (StringUtils.isNotEmpty(jsonObject.getString("remark"))) {
                scProOrder.setRemark(jsonObject.getString("remark"));
                systemRecord.setRemarks(jsonObject.getString("remark"));//备注记录
                //最新备注时间
                scProOrder.setLastRemarkTime(date);
                scProOrder.setLastRemark(jsonObject.getString("remark"));
            }
            scProOrder.setBeforeStatus(scProOrder.getStatus());//废单之前的状态
            scProOrder.setAuditorId(Long.parseLong(userAuditor.get("id").toString()));
            scProOrder.setAuditorName(userAuditor.get("realName").toString().concat(userAuditor.get("loginName").toString()));
            scProOrder.setAbandonReasonTime(date); //申请时间
            scProOrder.setAbandonReason(jsonObject.getString("applyReasonCode")); //申请类型
            scProOrder.setAbandonUserId(userEntity.getId()); //申请人ID
            scProOrder.setAbandonUser(userEntity.getRealName() + userEntity.getLoginName()); //申请人
            scProOrder.setStatus(ScProductConstant.RZSCORDER_STATUS07); //废单待审核
            scProOrder.setAbandonReasonNum(0);
            this.updateOpt(scProOrder, userEntity);

//            productOrders.add(scProOrder);
            //更新生产订单
           productOrderDao.updateByPrimaryKeySelective(scProOrder);
            //记录
            systemRecord.setWorkId(scProOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            systemRecord.setOperateType("11");//操作类型 : 废单
            systemRecord.setSource("2");//来源生产
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(organizationEntity.getId());
            systemRecord.setOperaterOrgName(organizationEntity.getName());
            systemRecord.setOperateTime(date);
            systemRecords.add(systemRecord);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(scProOrder.getId());
            customerRecord.setTableNo(scProOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE9);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent(jsonObject.getString("remark"));
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(scProOrder,null,userEntity);
        }
        //批量更新订单状态
//        productOrderDao.updateBatchById(productOrders);
        //插入操作日志
        systemRecordService.saveRecords(systemRecords);
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 暂缓
     * @Date 14:19 2018/12/27
     * @Param
     **/

    public void suspendReasonOrder(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        OrganizationEntity organizationEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "备注为空，请填写备注");
        ValidateUtils.isTrue(jsonObject.getString("remark").length()<=500, ProductOrderExcption.class, "备注内容不能超过500，请核查后再提交");
        ValidateUtils.strNotEmpty(jsonObject.getString("suspendReasonCode"), ProductOrderExcption.class, "暂缓原因为空，请选择暂缓原因");
        Map applyReason = commonMangerExtService.getTreeBookObj(jsonObject.getString("suspendReasonCode"));
        ValidateUtils.strNotEmpty(applyReason, ProductOrderExcption.class, "未查询到选择的暂缓理由，请重新选择");
        List<Long> scProductOrderIdList = new ArrayList<>();
        String idsStr = jsonObject.getString("ids");
        JSONArray ids = JSONArray.parseArray(idsStr);
       // JSONArray ids = jsonObject.getJSONArray("ids");
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
//        ValidateUtils.isTrue(ids.size() <= 10, ProductOrderExcption.class, "最多选择10条数据");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条数据` ");
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(scProOrderList, ProductOrderExcption.class, "未查询生产订单，请刷新列表！");
        List<String> statusList = new ArrayList<>();
        statusList.add(ScProductConstant.RZSCORDER_STATUS05); //退单待审核
        statusList.add(ScProductConstant.RZSCORDER_STATUS09);//退单驳回
        statusList.add(ScProductConstant.RZSCORDER_STATUS10);//废单驳回
        statusList.add(ScProductConstant.RZSCORDER_STATUS06);//已退单
        statusList.add(ScProductConstant.RZSCORDER_STATUS14);//待分配
        statusList.add(ScProductConstant.RZSCORDER_STATUS03);//暂缓
        statusList.add(ScProductConstant.RZSCORDER_STATUS07);//废单待审核
        statusList.add(ScProductConstant.RZSCORDER_STATUS05);//退单待审核
        statusList.add(ScProductConstant.RZSCORDER_STATUS17);//生产完结
        statusList.add(ScProductConstant.RZSCORDER_STATUS20);//强制完结
        statusList.add(ScProductConstant.RZSCORDER_STATUS19);//超期完结
        statusList.add(ScProductConstant.RZSCORDER_STATUS08);//已废单
        for (ProductOrder scProOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");
            //先判断状态再判断人员权限
            ValidateUtils.isTrue(!statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "订单" + scProOrder.getScProductOrderNo() + "当前状态不能操作暂缓，请刷新列表！");
            ValidateUtils.isTrue(userEntity.getId().equals(scProOrder.getFlowUserId()), ProductOrderExcption.class, "没有订单" + scProOrder.getScProductOrderNo() + "的操作权限");
        }
//        List<ProductOrder> productOrders = new ArrayList<>();
//        List<SystemRecord> systemRecords = new ArrayList<>();
        SystemRecord systemRecord = null;
        Date date = new Date();
        for (ProductOrder scProOrder : scProOrderList) {
            systemRecord = new SystemRecord();
            if (StringUtils.isNotEmpty(jsonObject.getString("remark"))) {
                scProOrder.setRemark(jsonObject.getString("remark"));
                systemRecord.setRemarks(jsonObject.getString("remark"));//备注记录
                //最新备注时间
                scProOrder.setLastRemarkTime(date);
                scProOrder.setLastRemark(jsonObject.getString("remark"));
            }
            scProOrder.setSuspendTime(date); //暂缓时间
            scProOrder.setSuspendReason(jsonObject.getString("suspendReasonCode")); //暂缓类型
            scProOrder.setStatus(ScProductConstant.RZSCORDER_STATUS03); //暂缓
            this.updateOpt(scProOrder, userEntity);
            productOrderDao.updateByPrimaryKeySelective(scProOrder);

            ProductTimeStatus scProductTimeStatus = productTimeStatusDao.selectByPrimaryKey(scProOrder.getId());
            if (scProductTimeStatus == null) {
                scProductTimeStatus = productTimeStatusService.insertProductStatus(scProOrder);
            }
            if (scProductTimeStatus != null) {
                scProductTimeStatus.setFlag(0);
                scProductTimeStatus.setStartSuspendTime(date); //暂停开始时间
                this.updateOpt(scProductTimeStatus, userEntity);
                productTimeStatusDao.updateByPrimaryKeySelective(scProductTimeStatus);
            }
            //记录
            systemRecord.setWorkId(scProOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            systemRecord.setOperateType("14");//操作类型 : 暂缓
            systemRecord.setSource("2");//来源生产
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(organizationEntity.getId());
            systemRecord.setOperaterOrgName(organizationEntity.getName());
            systemRecord.setOperateTime(date);
            systemRecord.setRemarks(jsonObject.getString("remark"));
            systemRecordDao.insert(systemRecord);

            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(scProOrder.getId());
            customerRecord.setTableNo(scProOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE11);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent(jsonObject.getString("remark"));
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(scProOrder,null,userEntity);
        }
    }


    /**
     * 验证当前用户是否可以操作该订单
     *
     * @param id          主订单id operate
     * @param operateType 操作类型
     * @return
     * @author: chenzaidong
     */
    public void validationUpdateNode(Long id, String operateType, String userLoginName) {
        //查询当前登录       用户
        UserEntity userEntity = searchUtils.getcurrUser(new HashMap() {{
            put("userLoginName", userLoginName);
        }});
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");

        //查询主订单
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "生产订单ID不能为空！");
        ProductOrder productOrder = this.productOrderDao.selectByPrimaryKey(id);
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到此生产主订单，请刷新列表！");
        //查询当前订单办理人
        List<Long> assis = new ArrayList<>();
        //流程人员id
        assis.add(productOrder.getFlowUserId());
        switch (operateType) {
            case "openUpdateNode":
                //协单人员(只有流程人员才阔以添加协单人员)
                HashMap<String, Object> map = new HashMap<>();
                map.put("scProductOrderId", productOrder.getId());
                List<Assistant> assistantList = assistantDao.query(map);
                if (assistantList.size() >= 1) {
                    for (Assistant assistant : assistantList) {
                        assis.add(assistant.getAssistUserId());
                    }
                }
                ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员/协单人员，不能进行该操作！");
                break;
            case "updateAssist":
                ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员，不能进行该操作！");
                break;
            case "updateCurrentChannel":
                ValidateUtils.isTrue(assis.contains(userEntity.getId()), ProductOrderExcption.class, "您不是该订单的流程人员，不能进行该操作！");
                break;
        }
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02), ProductOrderExcption.class
                , "此订单当前状态不是办理中不能操作该订单，请刷新列表！");


    }


    /**
     * 根据id查询主订单
     *
     * @param id
     * @return
     */
    public ProductOrder selectByPrimaryKey(Long id) {
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "未查询到对应订单");
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(id);
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到对应订单");
        return productOrder;
    }


    /**
     * 修改协单人员操作的节点
     *
     * @param scAssistants  协办记录表
     * @param scProductNode 节点
     * @param userEntity    当前登录用户
     * @author: chenzaidong
     */
    public void updateScAssistants(List<Assistant> scAssistants, ProductNode scProductNode, UserEntity userEntity) {
        for (Assistant assistant : scAssistants) {
            if (userEntity.getId().longValue() == assistant.getAssistUserId()) {
                assistant.setLatestEndNodeName(scProductNode.getName());
                assistant.setLatestEndNodeId(scProductNode.getId());
                assistant.setLatestEndNodeTime(new Date());
                updateOpt(assistant, userEntity);
                assistantDao.updateByPrimaryKey(assistant);
            }
        }
    }


    /**
     * 更新主订单状态
     *
     * @param productOrder      主订单
     * @param productTimeStatus 超期数据
     * @return
     * @author: chenzaidong
     */
    @Transactional
    public ProductOrder getScProductConstant(ProductOrder productOrder, ProductTimeStatus productTimeStatus) {
        //部分产品按原流程进行
        TreeBook treeBook = treeBookService.getTreeBookByCode("RZSC_AUDIT_END_OUT_PRODUCT");
        if(null == treeBook){
            throw new CommonExcption("完结待审核未配置需排除的产品字典");
        }
        List<String> ids = Arrays.asList(treeBook.getExt1().split(","));
        if(ids.contains(productOrder.getProductId().toString())){
            if ("强制完结".equals(productOrder.getLatestEndNodeName())) {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS20); //强制完结
                productOrder.setCompletedTime(new Date());
            }
            //订单正常完结且没有超期的
            if ("完结".equals(productOrder.getLatestEndNodeName()) && ScProductConstant.NORMAL.equals(productTimeStatus.getOrderTimeStatus())) {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS17);//生产完结
                productOrder.setCompletedTime(new Date());
            }//订单正常完结且已经超期的
            else if ("完结".equals(productOrder.getLatestEndNodeName()) && ScProductConstant.TIME_OUT.equals(productTimeStatus.getOrderTimeStatus())) {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS19); //超期完结
                productOrder.setCompletedTime(new Date());
            }
        }else{
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS22); //完结待审核
        }
        productOrder.setCompletedTime(new Date());
        return productOrder;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 保存分配
     * @Date 17:19 2018/12/26
     * @Param
     **/
    @Transactional
    public void allocateOrder(String params) {

        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);//当前操作人
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        Map userEntityDep = commonMangerExtService.findOrg(userEntity.getOrgId());
        List<Long> scProductOrderIdList = new ArrayList<>();
        JSONArray ids = jsonObject.getJSONArray("ids");
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
//        ValidateUtils.isTrue(ids.size() <= 10, ProductOrderExcption.class, "最多选择10条数据");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据` ");
        Map flowUser = cmsService.findUser(jsonObject.getLong("flowUserId"));
        ValidateUtils.strNotEmpty(flowUser, ProductOrderExcption.class, "未查询到选择的流程人员，请重新选择流程人员！");
        OrganizationEntity organizationEntity = organizationManager.findOrgEntityByOrgId(Long.parseLong(flowUser.get("orgId").toString()));
        ValidateUtils.strNotEmpty(organizationEntity, ProductOrderExcption.class, "未查询到选择的流程人员，请从新选择流程人员！");
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        Map busDep = commonMangerExtService.findBusDeptById(organizationEntity.getId());
        Map flowUserBusDep = commonMangerExtService.findBusDeptById(Long.valueOf(flowUser.get("orgId").toString()));
        ValidateUtils.strNotEmpty(busDep, ProductOrderExcption.class, "未查询到当前登录人所属事业部");
        ValidateUtils.strNotEmpty(flowUserBusDep, ProductOrderExcption.class, "未查询到当前所选流程人员所属事业部");
        ValidateUtils.isTrue(Long.valueOf(flowUserBusDep.get("id").toString()).equals(Long.valueOf(busDep.get("id").toString())), ProductOrderExcption.class, "当前所选流程人员与当前登录人所属事业部不同，不能进行分配");
        //获取本部门及所有下属部门ID
        List<Long> orderIdList = new ArrayList<>();
        List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(Long.valueOf(busDep.get("id").toString()));
        for (ProductOrder scProOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(scProOrder, ProductOrderExcption.class, "未查询到生产订单，请刷新列表！");
            ValidateUtils.isTrue(childOrganizationList.contains(scProOrder.getProductOrgId()), ProductOrderExcption.class, "没有生产编号为" + scProOrder.getScProductOrderNo() + "订单的的操作权限");
            List<String> statusList = new ArrayList<>();
            statusList.add(ScProductConstant.RZSCORDER_STATUS14); //待分配
            ValidateUtils.isTrue(statusList.contains(scProOrder.getStatus()), ProductOrderExcption.class, "此订单当前状态不能进行分配，请刷新列表！");
            orderIdList.add(scProOrder.getId());
        }
//        String allotWay = param.get("allotWay").toString();//分配方式
        List<ProductOrder> productOrders = new ArrayList<>();
        List<SystemRecord> systemRecords = new ArrayList<>();
        List<AllotRecord> allotRecordList = new ArrayList<>();
        Date date = new Date();
        ProductOrder proOrder = new ProductOrder();
        proOrder.setFlowUserId(Long.valueOf(flowUser.get("id").toString()));
        proOrder.setFlowUserName(flowUser.get("realName").toString().concat(flowUser.get("loginName").toString()));
        proOrder.setFlowUserOrgId(Long.valueOf(flowUser.get("orgId").toString()));
        proOrder.setFlowUserOrgName(flowUser.get("orgName").toString());
        proOrder.setAllotUserId(userEntity.getId());
        proOrder.setAllotUserName(userEntity.getRealName() + userEntity.getLoginName());
        proOrder.setAllotUserOrgId(userEntity.getOrgId());
        proOrder.setAllotUserOrgName(userEntityDep.get("name").toString());
        proOrder.setAllotDate(date);
        proOrder.setAllotWay(ScProductConstant.ALLOT_TO_FLOW_USER);
        proOrder.setStatus(ScProductConstant.RZSCORDER_STATUS01);
        proOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_ALLOT);
        this.updateOpt(proOrder, userEntity);
        productOrderDao.updateBatchByIds(proOrder, orderIdList);
        for (ProductOrder scProOrder : scProOrderList) {
            //记录
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setWorkId(scProOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            systemRecord.setOperateType("5");//操作类型 : 分配
            systemRecord.setSource("2");//来源生产
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setRemarks("分单人员：" + userEntity.getRealName() + userEntity.getLoginName() + "将该订单分配给:" + flowUser.get("realName") + flowUser.get("loginName"));
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(organizationEntity.getId());
            systemRecord.setOperaterOrgName(organizationEntity.getName());
            systemRecord.setBeOperaterId(Long.valueOf(flowUser.get("id").toString()));
            systemRecord.setBeOperaterName(flowUser.get("realName").toString() + flowUser.get("loginName").toString());
            systemRecord.setBeOperaterOrgId(organizationEntity.getId());
            systemRecord.setBeOperaterOrgName(organizationEntity.getName());
            systemRecord.setOperateTime(date);
            systemRecordService.save(systemRecord);


            //超期计算
            ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(scProOrder.getId());
            if (timestatus == null) {
                timestatus = productTimeStatusService.insertProductStatus(scProOrder);
            }
            if (timestatus != null) {
                int i = DateUtils.compare_date(new Date(), timestatus.getDistributionEndTime());
                if (i == 1) {
                    timestatus.setDistributionTimeOutStatus(ScProductConstant.TIME_OUT);
                } else {
                    timestatus.setDistributionTimeOutStatus(timestatus.getDistributionTimeOutStatus());
                }
                timestatus.setReceiveStartTime(new Date());
                timestatus.setReceiveProcessTime(1);
                try {
                    timestatus.setReceiveEndTime(DateUtils.dateAddDayJs(new Date(), 1));
                    timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                productTimeStatusDao.updateByPrimaryKeySelective(timestatus);
            }

            //订单分配记录
            AllotRecord allotRecord = new AllotRecord();
            allotRecord.setId(DggKeyWorker.nextId());
            allotRecord.setScProductOrderId(scProOrder.getId());
            allotRecord.setAllotUserId(Long.valueOf(flowUser.get("id").toString()));
            allotRecord.setAllotUserName(flowUser.get("realName").toString().concat(flowUser.get("loginName").toString()));
            allotRecord.setAllotOrgId(Long.valueOf(flowUser.get("orgId").toString()));
            allotRecord.setAllotOrgName(flowUser.get("orgName").toString());
            allotRecord.setAllotWay(ScProductConstant.ALLOT_TO_FLOW_USER);
            this.saveOpt(allotRecord, userEntity);
            allotRecordDao.insertSelective(allotRecord);


            try {//分配发送消息 失败就算了
                String[] msgs = new String[]{scProOrder.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                UserEntity flowerUserEntity = userservice.findUserById(Long.parseLong(flowUser.get("id").toString()));
                List<UserEntity> users = new ArrayList<>();
                users.add(flowerUserEntity);//接收人
                commonService.sendMsgByAsynchronous(users, msgs, MsgConstant.RZSC_SC_ALLOCATE);//分配模板
            } catch (Exception e) {
                e.printStackTrace();
            }
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(scProOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(scProOrder.getId());
            customerRecord.setTableNo(scProOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE2);
            customerRecord.setCreaterId(userEntity.getId());
            customerRecord.setContent("分配订单");
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(scProOrder,null,userEntity);
//            allotRecordList.add(allotRecord);
        }
        //批量更新订单状态
//        productOrderDao.updateBatchById(productOrders);
        //批量插入分配记录
//        allotRecordDao.insertSelectiveBatch(allotRecordList);
        //插入操作日志
//        systemRecordService.saveRecords(systemRecords);
    }

    /**
     * 根据主订单id查询协助办理人员
     *
     * @param id
     * @return
     * @Author chenzaidong
     */
    public List<Assistant> queyScAssistantList(Long id) {
        ValidateUtils.strNotEmpty(id, ProductOrderExcption.class, "生产订单id不能为空！");
        List<Assistant> assistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", id);
        }});
        return assistantList;
    }


    /**
     * 保存添加协单人员
     *
     * @param productOrderId 主订单id
     * @param assistIds      协办人员id集合
     * @Author chenzaidong
     */
    @Transactional
    public void updateAssist(Long productOrderId, String assistIds) {

        ValidateUtils.strNotEmpty(productOrderId, ProductOrderExcption.class, "生产订单ID为空,请刷新页面重试！");
        ProductOrder scProductOrder = this.productOrderDao.selectByPrimaryKey(productOrderId);
        ValidateUtils.strNotEmpty(scProductOrder, ProductOrderExcption.class, "未查询到此生产订单，请刷新列表！");

        //只有这个办理中，可以增加协助办理人员
        ValidateUtils.isTrue(scProductOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02), ProductOrderExcption.class, "该生产订单当前状态不能添加协单人员！");


        //查询该生产订单相关的协单人员
        List<Assistant> scAssistants = this.assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", productOrderId);
        }});

        //最新协办人员id集合
        ArrayList<String> assistanslist = new ArrayList<>();
        if (!net.dgg.rz.common.utils.StringUtils.isEmpty(assistIds)) {
            String[] split = assistIds.split(",");
            assistanslist = new ArrayList<>(Arrays.asList(split));
        }

        //验证协单人员最多只能添加5个
        ValidateUtils.isTrue(assistanslist.size() <= 5, ProductOrderExcption.class, "协单人员最多只能添加5个！");
        //验证协单人员中是否都是该生产单事业部下的人
        //获取本部门及所有下属部门ID
        //List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(scProductOrder.getProductOrgId());
        List<String> xdList = new ArrayList<>();
        if (scAssistants != null && !scAssistants.isEmpty()) {
            for (Assistant scAssistant : scAssistants) {
                xdList.add(scAssistant.getAssistUserId() + "");
            }
        }

        for (int i = 0; i < scAssistants.size(); i++) {
            Assistant assistant = scAssistants.get(i);//获取当前办理人名单
            if (assistanslist.contains(assistant.getAssistUserId().toString())) {//最新协办人以前存在
                assistanslist.remove(assistant.getAssistUserId().toString());//从协办人员集合中移除
            } else {//最新名单不包含以前的协办人员
                assistantDao.deleteByPrimaryKey(assistant.getId());//删除协办人员
                //保存操作记录
                Map flowUser = cmsService.findUser(assistant.getAssistUserId());
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setBeOperaterId(assistant.getAssistUserId());
                systemRecord.setBeOperaterName(flowUser.get("realName") + "" + flowUser.get("loginName"));
                systemRecord.setBeOperaterOrgId(Long.parseLong(flowUser.get("orgId") + ""));
                systemRecord.setBeOperaterOrgName(flowUser.get("orgName") + "");
                systemRecord.setWorkId(productOrderId);
                systemRecord.setWorkTableName("rzsc_assistant");
                systemRecord.setRemarks("删除协单人员:" + flowUser.get("realName") + "" + flowUser.get("loginName"));
                systemRecord.setOperateType("16");//操作类型 : 取消协单
                systemRecord.setSource("2");//来源生产
                systemRecordService.save(systemRecord);
            }
        }

        //集合中的人员还存在的id是新增
        for (int i = 0; i < assistanslist.size(); i++) {
            UserEntity userEntity = userservice.findUserById(Long.parseLong(assistanslist.get(i)));
            if (userEntity == null) {
                throw new ProductOrderExcption("新增加的协单人员不存在，请刷新列表");
            }
            OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());

            Assistant assistant = new Assistant();
            assistant.setId(DggKeyWorker.nextId());//设置id
            assistant.setAssistUserId(userEntity.getId());//办理人id
            assistant.setScProductOrderId(productOrderId);//主订单id
            assistant.setAssistUserName(userEntity.getRealName() + userEntity.getLoginName());//办理人名称
            assistant.setLatestEndNodeId(scProductOrder.getLatestEndNodeId());//设置最后更新的节点
            if (null != org) {
                assistant.setAssistUserOrgId(org.getId());//设置协办人部门id
                assistant.setAssistUserOrgName(org.getName());//设置协办人部门名称
            }
            assistantDao.insert(assistant);
            SystemRecord systemRecord = new SystemRecord();
            Map flowUser = cmsService.findUser(assistant.getAssistUserId());
            systemRecord.setBeOperaterId(userEntity.getId());
            systemRecord.setBeOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setBeOperaterOrgId(userEntity.getOrgId());
            systemRecord.setBeOperaterOrgName(flowUser.get("orgName") + "");
            systemRecord.setWorkId(productOrderId);
            systemRecord.setWorkTableName("rzsc_assistant");
            systemRecord.setRemarks("增加协单人员:" + userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperateType("15");//操作类型 : 添加协单
            systemRecord.setSource("2");//来源生产
            systemRecordService.save(systemRecord);

        }
        StringBuffer sb = new StringBuffer();
        ArrayList<String> assistanslist1 = new ArrayList<>();
        if (!net.dgg.rz.common.utils.StringUtils.isEmpty(assistIds)) {
            String[] split = assistIds.split(",");
            assistanslist1 = new ArrayList<>(Arrays.asList(split));
        }
        if (assistanslist1.size() > 0) {
            for (int i = 0; i < assistanslist1.size(); i++) {
                UserEntity userEntity = userservice.findUserById(Long.parseLong(assistanslist1.get(i)));
                if (userEntity == null) {
                    throw new ProductOrderExcption("新增加的协单人员不存在，请刷新列表");
                }
                if (i != assistanslist1.size() - 1) {
                    sb.append(userEntity.getRealName() + userEntity.getLoginName()).append(",");
                } else {
                    sb.append(userEntity.getRealName() + userEntity.getLoginName());
                }

            }
        } else {
            sb.append("");
        }
        ProductOrder p = new ProductOrder();
        p.setId(scProductOrder.getId());
        p.setAssistantName(sb.toString());
        this.productOrderDao.updateByPrimaryKeySelective(p);
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(scProductOrder.getCustomerId());
        customerRecord.setTableName("rzsc_product_order");
        customerRecord.setTableId(scProductOrder.getId());
        customerRecord.setTableNo(scProductOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE10);
        UserEntity user = sessionManager.getCurrentUser();
        customerRecord.setCreaterId(user.getId());
        customerRecord.setContent("添加协单人员");
        MQMessageSendUtil.ucMessageSend(customerRecord);
        //同步生产单状态给企大宝
        MQMessageSendUtil.qdsMessageSend(scProductOrder,null,user);
    }

    /**
     * 完结待审核-审核
     */
    public void auditOrder(String params){
        JSONObject jsonObject = JSON.parseObject(params);
        //获取当前登录用户
        UserEntity userEntity = sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(userEntity, FlowNodeExcption.class, "未获取到登陆人，请重新登录！");
        String ids = jsonObject.getString("ids");
        String remark = jsonObject.getString("remark");
        String auditResult = jsonObject.getString("auditResult");
        JSONArray jsonArray = JSONArray.parseArray(ids);
        if(jsonArray.size() < 1){
            throw new CommonExcption("请至少保留一个订单！");
        }
        List<Long> idArray = jsonArray.toJavaList(Long.class);
        List<ProductOrder> productOrders = selectByOrderIds(idArray);
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        for (ProductOrder productOrder : productOrders){
            ProductNodeOperating productNodeOperating = new ProductNodeOperating();
            productNodeOperating.setId(DggKeyWorker.nextId());//设置id
            productNodeOperating.setRemarksType(2);   //(记录类型  1：节点更新，2：备注)
            productNodeOperating.setScProductOrderId(productOrder.getId());//主订单id
            productNodeOperating.setScProductOrderNo(productOrder.getScProductOrderNo());//生产订单编号
            productNodeOperating.setFlowOrgId(org.getId());//部门id
            productNodeOperating.setFlowOrgName(org.getName());//部门名称
            productNodeOperating.setFlowUserId(productOrder.getFlowUserId());//流程人员id
            productNodeOperating.setFlowUserName(productOrder.getFlowUserName());//流程人员名字
            productNodeOperating.setOrderStatus(productOrder.getStatus());//生产订单状态
//            productNodeOperating.setNodeId();//节点id
            productNodeOperating.setNodeName("完结审核");//节点名称
            productNodeOperating.setNodeOpetateTime(new Date());//节点完成时间
            this.saveOpt(productNodeOperating,userEntity);
            OrganizationEntity operatedOrgan = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
            productNodeOperating.setUpdaterOrgName(operatedOrgan.getName());
            productNodeOperating.setCreaterOrgName(operatedOrgan.getName());
            //审核通过
            if("0".equals(auditResult)){
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS17);
                productOrder.setCompletedTime(new Date());
                productNodeOperating.setRemark("审核通过："+remark);
            }else{
                //审核不通过
                productNodeOperating.setRemark("审核驳回："+remark);
                //查询放款节点
                List<ProductNode> productNodeList = new ArrayList<>();
                ProductNode productNode = null;
                if(net.dgg.rz.common.utils.StringUtils.isNotEmpty(productOrder.getNodeJson())){
                    List<ProductNode> productNodes = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
                    ValidateUtils.strNotEmpty(productNodeList, ProductOrderExcption.class, "节点不存在，请刷新后重试");//节点不等于空
                    for(ProductNode p : productNodes){
                        if("放款".equals(p.getName())){
                            productNodeList.add(p);
                            productNode = p;
                        }
                    }
                }else{
                    //节点id查询节点
                    productNodeList = productNodeDao.query(new HashMap<String, Object>() {{
                        put("name", "放款");
                    }});
                    ValidateUtils.strNotEmpty(productNodeList, ProductOrderExcption.class, "节点不存在，请刷新后重试");//节点不等于空
                    productNode = productNodeList.get(0);
                }
                //驳回后强行默认为放款节点
                productOrder.setLatestEndNodeId(productNode.getId()); //放款节点id
                productOrder.setLatestEndNodeName(productNode.getName()); //放款节点
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS02);
            }
            productNodeOperatingDao.insert(productNodeOperating);
            this.updateOpt(productOrder, userEntity);
            productOrderDao.updateBatchById(productOrder);
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(productOrder.getCustomerId());
            customerRecord.setTableName("rzsc_product_order");
            customerRecord.setTableId(productOrder.getId());
            customerRecord.setTableNo(productOrder.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE4);
            customerRecord.setCreaterId(userEntity.getId());
            //设置备注
            customerRecord.setContent(remark);
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
        }
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 退单审核
     * @Date 11:24 2018/12/28
     * @Param
     **/
    public void abandonAudit(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity userOrgEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(jsonObject.getString("id"), ProductOrderExcption.class, "未获取到订单数据，请重新选择后提交");
        ProductOrder productOrder = this.selectByPrimaryKey(Long.valueOf(jsonObject.getString("id")));
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到订单数据，请重新选择后提交！");
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(userOrgEntity, ProductOrderExcption.class, "未查询到当前登录人部门，请重新登录！");
        ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "备注为空，请填写备注后再提交");
        ValidateUtils.isTrue(jsonObject.getString("remark").length()<=500, ProductOrderExcption.class, "备注内容不能超过500，请核查后再提交");

//        Map auditResult = commonMangerExtService.getTreeBookObj();
        ValidateUtils.strNotEmpty(jsonObject.getString("auditResult"), ProductOrderExcption.class, "未获取到审核结果，请重新提交");
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS05), ProductOrderExcption.class, "订单状态已改变，请刷新页面");
        //验证审核人是不是当前登录人
        ValidateUtils.isTrue(productOrder.getAuditorId().equals(userEntity.getId()), ProductOrderExcption.class, "您没有权限审核这条生产单");
        Map map = new HashMap();
        ProductNodeFlow nodeFlow = null;
        Long serialId = commonService.getSerialId(productOrder.getProductId());
        if(net.dgg.rz.common.utils.StringUtils.isNotEmpty(productOrder.getNodeJson())){
            map.put("productId", serialId);
            map.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            map.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            nodeFlow = apiProductionService.getNodeFlow(map);
        }else{
            map.put("flowId", productOrder.getNodeFlowId());
            nodeFlow = flowNodeService.findFlowById(map);
        }
        Date date = new Date();
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setWorkTableName("rzsc_product_order");

        systemRecord.setSource("2");//来源生产
        systemRecord.setId(DggKeyWorker.nextId());
        systemRecord.setOperaterId(userEntity.getId());
        systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
        systemRecord.setOperaterOrgId(userOrgEntity.getId());
        systemRecord.setOperaterOrgName(userOrgEntity.getName());
        systemRecord.setOperateTime(date);
        //同意
        if ("0".equals(jsonObject.getString("auditResult"))) {
            //不是最后一次审核
            int examineGrade = nodeFlow.getExamineGrade() == null ? 1 : nodeFlow.getExamineGrade();
            int abandonReasonNum = productOrder.getAbandonReasonNum() == null ? 0 : productOrder.getAbandonReasonNum();
            if (examineGrade > abandonReasonNum + 1) {
                Map nextAuditor = cmsService.findUser(jsonObject.getLong("nextAuditorId"));
                ValidateUtils.strNotEmpty(nextAuditor, ProductOrderExcption.class, "未查询到选择的下一审核人，请重新选择下一审核人！");
                OrganizationEntity nextAuditorOrgEntity = organizationManager.findOrgEntityByOrgId(Long.parseLong(nextAuditor.get("orgId").toString()));
                ValidateUtils.strNotEmpty(nextAuditorOrgEntity, ProductOrderExcption.class, "未查询到选择的下一审核人，请重新选择下一审核人！");
                productOrder.setAuditorId(Long.valueOf(nextAuditor.get("id").toString()));
                productOrder.setAuditorName(nextAuditor.get("realName").toString().concat(nextAuditor.get("loginName").toString()));
                productOrder.setAbandonReasonNum(productOrder.getAbandonReasonNum() + 1);
                productOrder.setLastRemark(jsonObject.getString("remark"));

                systemRecord.setOperateType("28");//操作类型 : 退单审核通过
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "审核通过:" + productOrder.getAbandonUser() + "提交的退单申请，" +
                        "还需审核" + (nodeFlow.getExamineGrade() - productOrder.getAbandonReasonNum()) + "次，下一审核人：" + nextAuditor.get("realName") + nextAuditor.get("loginName") + "。" + jsonObject.getString("remark"));
            }
            //最后一次审核通过
            else {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS06);
                productOrder.setReturnAbandonCompleteTime(date);
                productOrder.setAbandonReasonNum(productOrder.getAbandonReasonNum() + 1);
                productOrder.setLastRemark(jsonObject.getString("remark"));
                systemRecord.setOperateType("28");//操作类型 : 退单审核通过
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "审核通过:" + productOrder.getAbandonUser() + "提交的退单申请，" +
                        "退单审核完成。" + jsonObject.getString("remark"));
            }
        }
        //不同意（驳回）
        else {
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS09);
            productOrder.setReturnAbandonCompleteTime(date);
            productOrder.setLastRemark(jsonObject.getString("remark"));
            systemRecord.setOperateType("29");//操作类型 : 退单审核驳回
            systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "驳回:" + productOrder.getAbandonUser() + "提交的退单申请。" + jsonObject.getString("remark"));
        }
        this.updateOpt(productOrder, userEntity);
        productOrderDao.updateByPrimaryKeySelective(productOrder);
        systemRecordService.save(systemRecord);
        //同步生产单状态给企大宝
        MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO退单批量审核
     * @Date 16:36 2019/4/25
     * @Param
     **/
    public void abandonAuditMulity(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity userOrgEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(jsonObject.getString("ids"), ProductOrderExcption.class, "未获取到订单数据，请重新选择后提交");
        String idsStr = jsonObject.getString("ids");
        JSONArray ids = JSONArray.parseArray(idsStr);
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据` ");
        List<Long> scProductOrderIdList = new ArrayList<>();
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(scProOrderList, ProductOrderExcption.class, "未查询生产订单，请刷新列表！");
        Date date = new Date();
       for(ProductOrder productOrder:scProOrderList){
           //验证审核人是不是当前登录人
           ValidateUtils.isTrue(productOrder.getAuditorId().equals(userEntity.getId()), ProductOrderExcption.class, "您没有权限审核这条生产单");
           ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS05), ProductOrderExcption.class, "订单状态已改变，请刷新页面");
           //验证审核人是不是当前登录人

           SystemRecord systemRecord = new SystemRecord();
           systemRecord.setWorkId(productOrder.getId());
           systemRecord.setWorkTableName("rzsc_product_order");

           systemRecord.setSource("2");//来源生产
           systemRecord.setId(DggKeyWorker.nextId());
           systemRecord.setOperaterId(userEntity.getId());
           systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
           systemRecord.setOperaterOrgId(userOrgEntity.getId());
           systemRecord.setOperaterOrgName(userOrgEntity.getName());
           systemRecord.setOperateTime(date);

           Map<String, Long> map = new HashMap();
           map.put("flowId", productOrder.getNodeFlowId());
           ProductNodeFlow productNodeFlow = new ProductNodeFlow();
           productNodeFlow = productNodeFlowDao.queryFlowById(map);
           Integer examinGrade = new Integer(1);
           if (null != productNodeFlow) {
               examinGrade = productNodeFlow.getExamineGrade();
           }
           //同意
           if ("0".equals(jsonObject.getString("auditResult"))) {
               productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS06);
               productOrder.setReturnAbandonCompleteTime(date);
               productOrder.setAbandonReasonNum(examinGrade);
               productOrder.setLastRemark(jsonObject.getString("remark"));
               systemRecord.setOperateType("28");//操作类型 : 退单审核通过
               systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "批量审核通过:" + productOrder.getAbandonUser() + "提交的退单申请，" +
                       "退单审核完成。" );
           }
           //不同意（驳回）
           else {
               productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS09);
               productOrder.setReturnAbandonCompleteTime(date);
               productOrder.setLastRemark(jsonObject.getString("remark"));
               systemRecord.setOperateType("29");//操作类型 : 退单审核驳回
               systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "驳回:" + productOrder.getAbandonUser() + "提交的退单申请。" );
           }
           this.updateOpt(productOrder, userEntity);
           productOrderDao.updateByPrimaryKeySelective(productOrder);
           systemRecordService.save(systemRecord);
           //同步生产单状态给企大宝
           MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
       }

    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 废单审核
     * @Date 11:24 2018/12/28
     * @Param
     **/
    public void nullifyAudit(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity userOrgEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(jsonObject.getString("id"), ProductOrderExcption.class, "未获取到订单数据，请重新选择后提交");
        ProductOrder productOrder = this.selectByPrimaryKey(Long.valueOf(jsonObject.getString("id")));
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到订单数据，请重新选择后提交！");
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(userOrgEntity, ProductOrderExcption.class, "未查询到当前登录人部门，请重新登录！");
        ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "备注为空，请填写备注后再提交");
        ValidateUtils.isTrue(jsonObject.getString("remark").length()<=500, ProductOrderExcption.class, "备注内容不能超过500，请核查后再提交");
//        Map auditResult = commonMangerExtService.getTreeBookObj();
        ValidateUtils.strNotEmpty(jsonObject.getString("auditResult"), ProductOrderExcption.class, "未获取到审核结果，请重新提交");
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS07), ProductOrderExcption.class, "订单状态已改变，请刷新页面");
        //验证审核人是不是当前登录人
        ValidateUtils.isTrue(productOrder.getAuditorId().equals(userEntity.getId()), ProductOrderExcption.class, "您没有权限审核这条生产单");
        Map map = new HashMap();
        ProductNodeFlow nodeFlow = null;
        Long serialId = commonService.getSerialId(productOrder.getProductId());
        if(net.dgg.rz.common.utils.StringUtils.isNotEmpty(productOrder.getNodeJson())){
            map.put("productId", serialId);
            map.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            map.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            nodeFlow = apiProductionService.getNodeFlow(map);
        }else{
            map.put("flowId", productOrder.getNodeFlowId());
            nodeFlow = flowNodeService.findFlowById(map);
        }
        if (productOrder.getAbandonReasonNum() == null) {
            productOrder.setAbandonReasonNum(0);
        }
        Date date = new Date();
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setWorkTableName("rzsc_product_order");

        systemRecord.setSource("2");//来源生产
        systemRecord.setId(DggKeyWorker.nextId());
        systemRecord.setOperaterId(userEntity.getId());
        systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
        systemRecord.setOperaterOrgId(userOrgEntity.getId());
        systemRecord.setOperaterOrgName(userOrgEntity.getName());
        systemRecord.setOperateTime(date);
        //同意
        if ("0".equals(jsonObject.getString("auditResult"))) {
            //不是最后一次审核
            int examineGrade = nodeFlow.getExamineGrade() == null ? 1 : nodeFlow.getExamineGrade();
            int abandonReasonNum = productOrder.getAbandonReasonNum() == null ? 0 : productOrder.getAbandonReasonNum();
            if (examineGrade > abandonReasonNum + 1) {
                Map nextAuditor = cmsService.findUser(jsonObject.getLong("nextAuditorId"));
                ValidateUtils.strNotEmpty(nextAuditor, ProductOrderExcption.class, "未查询到选择的下一审核人，请重新选择下一审核人！");
                OrganizationEntity nextAuditorOrgEntity = organizationManager.findOrgEntityByOrgId(Long.parseLong(nextAuditor.get("orgId").toString()));
                ValidateUtils.strNotEmpty(nextAuditorOrgEntity, ProductOrderExcption.class, "未查询到选择的下一审核人部门信息，请重新选择下一审核人！");
                productOrder.setAuditorId(Long.valueOf(nextAuditor.get("id").toString()));
                productOrder.setAuditorName(nextAuditor.get("realName").toString().concat(nextAuditor.get("loginName").toString()));
                productOrder.setAbandonReasonNum(productOrder.getAbandonReasonNum() + 1);
                productOrder.setLastRemark(jsonObject.getString("remark"));
                systemRecord.setOperateType("30");//操作类型 : 废单审核通过
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "审核通过:" + productOrder.getAbandonUser() + "提交的废单申请，" +
                        "还需审核" + (nodeFlow.getExamineGrade() - productOrder.getAbandonReasonNum()) + "次，下一审核人：" + nextAuditor.get("realName") + nextAuditor.get("loginName") + "。" + jsonObject.getString("remark"));
            }
            //最后一次审核通过
            else {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS08);
                productOrder.setReturnAbandonCompleteTime(date);
                productOrder.setAbandonReasonNum(productOrder.getAbandonReasonNum() + 1);
                productOrder.setLastRemark(jsonObject.getString("remark"));
                systemRecord.setOperateType("30");//操作类型 : 废单审核通过
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "审核通过:" + productOrder.getAbandonUser() + "提交的废单申请，" +
                        "废单审核完成。" + jsonObject.getString("remark"));
            }
        }
        //不同意（驳回）
        else {
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS10);
            productOrder.setReturnAbandonCompleteTime(date);
            productOrder.setLastRemark(jsonObject.getString("remark"));
            systemRecord.setOperateType("31");//操作类型 : 退单审核驳回
            systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "驳回:" + productOrder.getAbandonUser() + "提交的废单申请。" + jsonObject.getString("remark"));
        }
        this.updateOpt(productOrder, userEntity);
        productOrderDao.updateByPrimaryKeySelective(productOrder);
        systemRecordService.save(systemRecord);
        //同步生产单状态给企大宝
        MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO废单批量审核
     * @Date 16:36 2019/4/25
     * @Param
     **/
    public void nullifyAuditMulity(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity userOrgEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(jsonObject.getString("ids"), ProductOrderExcption.class, "未获取到订单数据，请重新选择后提交");
        ValidateUtils.strNotEmpty(jsonObject.getString("auditResult"), ProductOrderExcption.class, "未获取到审核结果，请重新提交");
        String idsStr = jsonObject.getString("ids");
        JSONArray ids = JSONArray.parseArray(idsStr);
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据` ");
        List<Long> scProductOrderIdList = new ArrayList<>();
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
        ValidateUtils.strNotEmpty(scProOrderList, ProductOrderExcption.class, "未查询生产订单，请刷新列表！");
        Date date = new Date();
        for(ProductOrder productOrder:scProOrderList){
            //验证审核人是不是当前登录人
            ValidateUtils.isTrue(productOrder.getAuditorId().equals(userEntity.getId()), ProductOrderExcption.class, "您没有权限审核这条生产单");
            ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS07), ProductOrderExcption.class, "订单状态已改变，请刷新页面");
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setWorkId(productOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            //来源生产
            systemRecord.setSource("2");
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(userOrgEntity.getId());
            systemRecord.setOperaterOrgName(userOrgEntity.getName());
            systemRecord.setOperateTime(date);

            Map<String, Long> map = new HashMap(1);
            map.put("flowId", productOrder.getNodeFlowId());
            ProductNodeFlow productNodeFlow = new ProductNodeFlow();
            productNodeFlow = productNodeFlowDao.queryFlowById(map);
            Integer examinGrade = new Integer(1);
            if (null != productNodeFlow) {
                examinGrade = productNodeFlow.getExamineGrade();
            }
            //同意
            if ("0".equals(jsonObject.getString("auditResult"))) {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS08);
                productOrder.setReturnAbandonCompleteTime(date);
                productOrder.setAbandonReasonNum(examinGrade);
                productOrder.setLastRemark(jsonObject.getString("remark"));
                //操作类型 : 废单审核通过
                systemRecord.setOperateType("30");
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "批量审核通过:" + productOrder.getAbandonUser() + "提交的废单申请，" +
                        "废单审核完成。" );
            }
            //不同意（驳回）
            else {
                productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS10);
                productOrder.setReturnAbandonCompleteTime(date);
                productOrder.setLastRemark(jsonObject.getString("remark"));
                //操作类型 : 退单审核驳回
                systemRecord.setOperateType("31");
                systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "驳回:" + productOrder.getAbandonUser() + "提交的废单申请。" );
            }
            this.updateOpt(productOrder, userEntity);
            productOrderDao.updateByPrimaryKeySelective(productOrder);
            systemRecordService.save(systemRecord);
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(productOrder,null,userEntity);
        }

    }
    /**
     * 更新主订单
     *
     * @param productOrder 主订单对象
     */
    @Transactional
    public void orderInfoSave(ProductOrder productOrder) {
        UserEntity userEntity = this.sessionManager.getCurrentUser();//当前操作人
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        //订单信息
        ProductOrderDto order = productOrderDao.selectDtoByPrimaryKey(productOrder.getId());
        ValidateUtils.strNotEmpty(order, ProductOrderExcption.class, "未找到生产订单！");
        boolean isEdit = roleService.exitsOperate4User(userEntity.getId(),ScProductConstant.RZSC_OPERATION_EDIT);
        boolean orderStatus = ScProductConstant.RZSCORDER_STATUS19.equals(order.getStatus()) || ScProductConstant.RZSCORDER_STATUS20.equals(order.getStatus()) || ScProductConstant.RZSCORDER_STATUS17.equals(order.getStatus());
        if((userEntity.getId().equals(order.getFlowUserId()) && !orderStatus)||isEdit){
            this.updateOpt(productOrder, userEntity);
            productOrderDao.updateByPrimaryKeySelective(productOrder);
        }else {
            ValidateUtils.strNotEmpty(null, ProductOrderExcption.class, "当前生产订单已完结或无权修改！");
        }
    }

    /**
     * 更新渠道
     *
     * @param updateProductOrder 更新对象，insertProductOrder
     */
    @Transactional
    public void updateChannel(ProductOrder updateProductOrder, ProductOrder insertProductOrder) {
        UserEntity userEntity = this.sessionManager.getCurrentUser();//当前操作人
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        this.updateOpt(updateProductOrder, userEntity);
        productOrderDao.updateByPrimaryKeySelective(updateProductOrder);
        this.updateOpt(insertProductOrder, userEntity);
        productOrderDao.insertSelective(insertProductOrder);
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 退单、废单审核撤回预处理
     * @Date 11:24 2018/12/28
     * @Param
     **/
    public void preWithdrawn(String params) {
        UserEntity userEntity = this.sessionManager.getCurrentUser();
        JSONObject jsonObject = JSON.parseObject(params);
        JSONArray ids = jsonObject.getJSONArray("ids");
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
//        ValidateUtils.isTrue(ids.size() <= 10, ProductOrderExcption.class, "最多选择10条数据");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据");
        List<Long> scProductOrderIdList = new ArrayList<>();
        List<String> status = new ArrayList<>();
        status.add(ScProductConstant.RZSCORDER_STATUS07);
        status.add(ScProductConstant.RZSCORDER_STATUS05);
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);

        for (ProductOrder productOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(productOrder.getFlowUserId(), ProductOrderExcption.class, "没有查询到生产订单编号：" + productOrder.getOrderBusNo() + "的流程人员");
            ValidateUtils.strNotEmpty(productOrder.getStatus(), ProductOrderExcption.class, "没有查询到生产订单编号：" + productOrder.getOrderBusNo() + "的订单状");
            ValidateUtils.isTrue(productOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "没有生产订单编号：" + productOrder.getOrderBusNo() + "的操作权限");
            ValidateUtils.isTrue(status.contains(productOrder.getStatus()), ProductOrderExcption.class, "生产订单编号：" + productOrder.getOrderBusNo() + "状态已改变，请刷新页面后再试");
        }
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 退单、废单审核撤回
     * @Date 11:24 2018/12/28
     * @Param
     **/
    @Transactional(rollbackFor = Exception.class)
    public void withdrawn(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity organizationEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");

        String idsStr = jsonObject.getString("ids");
        JSONArray ids = JSONArray.parseArray(idsStr);
        ValidateUtils.strNotEmpty(ids, ProductOrderExcption.class, "生产订单ID为空！");
//        ValidateUtils.isTrue(ids.size() <= 10, ProductOrderExcption.class, "最多选择10条数据");
        ValidateUtils.isTrue(ids.size() != 0, ProductOrderExcption.class, "请至少选择一条要退回的数据");
        List<Long> scProductOrderIdList = new ArrayList<>();
        List<String> status = new ArrayList<>();
        status.add(ScProductConstant.RZSCORDER_STATUS07);
        status.add(ScProductConstant.RZSCORDER_STATUS05);
        for (Object id : ids) {
            scProductOrderIdList.add(Long.valueOf(id.toString()));
        }
        List<ProductOrder> scProOrderList = this.productOrderDao.selectByPrimaryKeys(scProductOrderIdList);

        for (ProductOrder productOrder : scProOrderList) {
            ValidateUtils.strNotEmpty(productOrder.getFlowUserId(), ProductOrderExcption.class, "没有查询到生产订单编号：" + productOrder.getOrderBusNo() + "的流程人员");
            ValidateUtils.strNotEmpty(productOrder.getStatus(), ProductOrderExcption.class, "没有查询到生产订单编号：" + productOrder.getOrderBusNo() + "的订单状");
            ValidateUtils.isTrue(productOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "没有生产订单编号：" + productOrder.getScProductOrderNo() + "的操作权限");
            ValidateUtils.isTrue(status.contains(productOrder.getStatus()), ProductOrderExcption.class, "生产订单编号：" + productOrder.getOrderBusNo() + "状态已改变，请刷新页面后再试");
        }
        Date date = new Date();
        List<SystemRecord> systemRecords = new ArrayList<>();
        for (ProductOrder productOrder : scProOrderList) {
            productOrder.setStatus(productOrder.getBeforeStatus());
            //撤回后重置审核次数及审核人
            productOrder.setAbandonReasonNum(0);
            productOrder.setAuditorId(null);
            productOrder.setAuditorName(null);
            this.updateOpt(productOrder, userEntity);

            ProductTimeStatus scProductTimeStatus = productTimeStatusDao.selectByPrimaryKey(productOrder.getId());
            if (scProductTimeStatus == null) {
                scProductTimeStatus = productTimeStatusService.insertProductStatus(productOrder);
            }
            if (scProductTimeStatus != null) {
                scProductTimeStatus.setFlag(1);
                this.updateOpt(scProductTimeStatus, userEntity);
                productTimeStatusDao.updateByPrimaryKeySelective(scProductTimeStatus);
            }


            SystemRecord systemRecord = new SystemRecord();
            //记录
            systemRecord.setWorkId(productOrder.getId());
            systemRecord.setWorkTableName("rzsc_product_order");
            systemRecord.setOperateType("20");//操作类型 : 撤回
            systemRecord.setSource("2");//来源生产
            systemRecord.setId(DggKeyWorker.nextId());
            systemRecord.setRemarks(userEntity.getRealName() + userEntity.getLoginName() + "撤回了退单/废单申请");
            systemRecord.setOperaterId(userEntity.getId());
            systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
            systemRecord.setOperaterOrgId(organizationEntity.getId());
            systemRecord.setOperaterOrgName(organizationEntity.getName());
            systemRecord.setOperateTime(date);
            systemRecords.add(systemRecord);
            productOrderDao.updateBatchById(productOrder);
        }
        systemRecordService.saveRecords(systemRecords);
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 变更审核人
     * @Date 11:24 2018/12/28
     * @Param
     **/
    public void changAuditor(String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        if(StringUtils.isEmpty(jsonObject.getString("id"))&&StringUtils.isEmpty(jsonObject.getString("ids"))){
            ValidateUtils.strNotEmpty(null, ProductOrderExcption.class, "未获取到订单数据，请重新选择后提交");
        }
        if(!StringUtils.isEmpty(jsonObject.getString("id"))){
            changeAuditorMethod(jsonObject);
        }else {
            JSONArray ids = JSON.parseArray(jsonObject.getString("ids"));
            if(ids != null && ids.size()>0){
                for (Object jsonArray:ids){
                    jsonObject.put("id",jsonArray);
                    changeAuditorMethod(jsonObject);
                }
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    void changeAuditorMethod(JSONObject jsonObject){
        UserEntity userEntity = searchUtils.getcurrUser(jsonObject);
        OrganizationEntity userOrgEntity = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());
        ProductOrder productOrder = this.selectByPrimaryKey(Long.valueOf(jsonObject.getString("id")));
        ValidateUtils.strNotEmpty(productOrder, ProductOrderExcption.class, "未查询到订单数据，请重新选择后提交！");
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(userOrgEntity, ProductOrderExcption.class, "未查询到当前登录人部门，请重新登录！");
        ValidateUtils.strNotEmpty(jsonObject.getString("remark"), ProductOrderExcption.class, "备注为空，请填写备注后再提交");
        ValidateUtils.isTrue(jsonObject.getString("remark").length()<=500, ProductOrderExcption.class, "备注内容不能超过500，请核查后再提交");
//        Map auditResult = commonMangerExtService.getTreeBookObj();
        ValidateUtils.strNotEmpty(jsonObject.getString("otherAuditorId"), ProductOrderExcption.class, "未获取到要更改的审核人，请重新提交");
        Map otherAuditor = cmsService.findUser(Long.parseLong(jsonObject.getString("otherAuditorId")));

        ValidateUtils.strNotEmpty(otherAuditor, ProductOrderExcption.class, "未获取到要更改的审核人，请重新提交");
        ValidateUtils.isTrue((productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS07)
                || productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS05)), ProductOrderExcption.class, "订单状态已改变，请刷新页面");
        ValidateUtils.isTrue(!productOrder.getAuditorId().equals(Long.parseLong(jsonObject.getString("otherAuditorId"))), ProductOrderExcption.class, "要更改的审核人为当前审核人");
        Map busDep = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(busDep, ProductOrderExcption.class, "未获取登录人所属事业部信息");
        ValidateUtils.strNotEmpty(otherAuditor.get("orgId"), ProductOrderExcption.class, "未获取到要更改的审核人的部门信息");
        Map otherAuditorBusDep = commonMangerExtService.findBusDeptById(Long.valueOf(otherAuditor.get("orgId").toString()));
        ValidateUtils.isTrue(Long.valueOf(otherAuditorBusDep.get("id").toString()).equals(Long.valueOf(busDep.get("id").toString())), ProductOrderExcption.class, "当前操作人与变更后审核人事业部不同，不能操作");
        ValidateUtils.isTrue(Long.valueOf(otherAuditorBusDep.get("id").toString()).equals(productOrder.getProductOrgId()), ProductOrderExcption.class, "变更审核人事业部不为当前订单所属事业部");
        Date date = new Date();
        productOrder.setAuditorId(Long.valueOf(otherAuditor.get("id").toString()));
        productOrder.setAuditorName(otherAuditor.get("realName").toString().concat(otherAuditor.get("loginName").toString()));
        productOrder.setLastRemark(jsonObject.getString("remark"));
        productOrder.setLastRemarkTime(date);
        this.updateOpt(productOrder, userEntity);

        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setWorkId(productOrder.getId());
        systemRecord.setWorkTableName("rzsc_product_order");
        systemRecord.setSource("2");//来源生产
        systemRecord.setId(DggKeyWorker.nextId());
        systemRecord.setOperaterId(userEntity.getId());
        systemRecord.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());
        systemRecord.setOperaterOrgId(userOrgEntity.getId());
        systemRecord.setOperaterOrgName(userOrgEntity.getName());
        systemRecord.setOperateTime(date);
        systemRecord.setOperateType("19");//操作类型 : 退单审核通过
        systemRecord.setRemarks("审核人员：" + userEntity.getRealName() + userEntity.getLoginName() + "变更:" + productOrder.getAbandonUser() + "提交的退单/废单申请的审核人，" +
                "变更为:" + otherAuditor.get("realName") + otherAuditor.get("loginName") + "备注" + jsonObject.getString("remark"));
        productOrderDao.updateByPrimaryKeySelective(productOrder);
        systemRecordService.apiSave(systemRecord,userEntity);
    }

    /**
     * 修改借贷人信息
     *
     * @param params
     * @return
     */
    @Transactional
    public void orderContactUpdate(Map params) {
        Integer state = 1;
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, CommonExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.isTrue(sessionUser.getId().equals(Long.parseLong(params.get("flowUserId") + "")), CommonExcption.class, "您不是当前流程人员，不能修改借贷人信息！");
        ValidateUtils.strNotEmpty(params.get("contactId"), CommonExcption.class, "借贷人ID为空！");
        OrderContact orderContact = orderContactDao.selectByPrimaryKey(Long.parseLong(params.get("contactId") + ""));
        ValidateUtils.strNotEmpty(orderContact, CommonExcption.class, "未查询到借贷人相关信息！");

        //借贷然是本人（orderConcactIsSelf 为1）时候需要判断多个借贷人的时候是否有其他借贷人的 orderConcactIsSelf的值为1
        if ("1".equals(params.get("orderConcactIsSelf") + "")) {
            List<OrderContact> orderContacts = orderContactDao.getListByOrderNo(orderContact.getOrderNo());
            for (OrderContact o : orderContacts) {
                if (state.equals(o.getIsSelf()) && !o.getId().equals(Long.parseLong(params.get("contactId") + ""))) {
                    throw new CommonExcption("不能同时存在2个及以上是客户本人");
                }
            }
        }
        orderContact.setName(params.get("orderConcactName") + "");//借贷人姓名
        /*orderContact.setLenderStatus(Integer.parseInt(params.get("orderConcactLenderStatus")+""));//身份*/
        orderContact.setIsSelf(Integer.parseInt(params.get("orderConcactIsSelf") + ""));//是否是客户本人
        if ("1".equals(params.get("IdCardState"))) {
            //判断同一个订单的借贷人身份证号码是否重复
            List<OrderContact> orderContacts = orderContactDao.getListByOrderNo(orderContact.getOrderNo());
            for (OrderContact o : orderContacts) {
                if (!o.getId().equals(Long.parseLong(params.get("contactId") + "")) && o.getCardId().equals(params.get("orderConcactCardId") + "")) {
                    throw new CommonExcption("同一个生产单多个借贷人的身份证号不能重复");
                }
            }
            orderContact.setCardId(params.get("orderConcactCardId") + "");//身份证号码
        }
        if ("1".equals(params.get("noState"))) {
            orderContact.setNo(desUtil.encrypt(params.get("orderConcactNo") + ""));//电话号码
        }
        orderContact.setContactMaritalStatus(params.get("orderConcactContactMaritalStatus") + "");//婚姻状况
        if (StringUtils.isNotBlank(params.get("orderConcactContactChildrenNum") + "")) {
            orderContact.setContactChildrenNum(Integer.parseInt(params.get("orderConcactContactChildrenNum") + ""));//子女情况（数量）
        }
        orderContact.setNoKnow(Integer.parseInt(params.get("orderConcactNoKnow") + ""));//家属是否知晓
        /*orderContact.setRelationshipOfCus(params.get("orderConcactRelationshipOfCus")+"");//与主借贷人关系*/
        orderContactDao.updateByPrimaryKeySelective1(orderContact);
        //操作记录日志
        SystemRecord record = new SystemRecord();
        //record.setId(DggKeyWorker.nextId());//id
        record.setSource("2");
        record.setWorkTableName("rzsc_order_contact");
        record.setWorkId(orderContact.getId());
        //record.setWorkNo(orderContact.getOrderNo());
        record.setOperateType("7");
        record.setRemarks(sessionUser.getRealName() + sessionUser.getLoginName() + "修改借贷人信息");
        systemRecordService.save(record);
    }

    /**
     * 根据借贷人ID获取身份证号码
     *
     * @param contactId
     * @return
     */
    @SuppressWarnings("all")
    public String getIdCardByContactId(String contactId) {
        ValidateUtils.strNotEmpty(contactId, CommonExcption.class, "借贷人ID为空！");
        OrderContact orderContact = orderContactDao.selectByPrimaryKey(Long.parseLong(contactId));
        ValidateUtils.strNotEmpty(orderContact, CommonExcption.class, "未查询到借贷人相关信息！");
        String IdCard = orderContact.getCardId();
        return IdCard;
    }

    /**
     * 根据客户ID获取身份证号码
     *
     * @param id
     * @return
     */
    @SuppressWarnings("all")
    public String getCustomerCardById(String id) {
        ValidateUtils.strNotEmpty(id, CommonExcption.class, "客户ID为空！");
        OrderCustomer customer = orderCustomerDao.selectByPrimaryKey(Long.parseLong(id));
        ValidateUtils.strNotEmpty(customer, CommonExcption.class, "未查询客户相关信息！");
        String IdCard = customer.getIdCard();
        return IdCard;
    }


    /**
     * 根据借贷人ID获取联系号码
     *
     * @param contactId
     * @return
     */
    @SuppressWarnings("all")
    public String getPhoneByContactId(String contactId) {
        ValidateUtils.strNotEmpty(contactId, CommonExcption.class, "借贷人ID为空！");
        OrderContact orderContact = orderContactDao.selectByPrimaryKey(Long.parseLong(contactId));
        ValidateUtils.strNotEmpty(orderContact, CommonExcption.class, "未查询到借贷人相关信息！");
        String phone = orderContact.getNo();
        phone = desUtil.decrypt(phone);
        return phone;
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 根据订单id查询所有生产订单
     * @Date 15:53 2019/3/21
     * @Param
     **/
    public List<ProductOrder> getListByOrderId(Long orderId, Long orderBusId, Long id) {
        ValidateUtils.strNotEmpty(orderId, ProductOrderExcption.class, "订单id为空！");
        List<ProductOrder> productOrders = productOrderDao.getListByOrderId(orderId, orderBusId, id);
        ValidateUtils.strNotEmpty(productOrders, ProductOrderExcption.class, "未查询到生产单");
        return productOrders;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 新增产品
     * @Date 10:05 2019/3/22
     * @Param
     **/
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(JSONObject params) throws IOException {
        //验证页面传递参数
        this.productChangeParams(params, ScProductConstant.RZSC_ORIGINCODE_PRO_ADD);
        Long scOrderId = params.getLong("id");
        String typeCode = params.getString("typeCode");
        Long productId = params.getLong("productId");
        //Long goodsId = params.getLong("goodsId");
        Long channelId = params.getLong("channelId");
        ValidateUtils.strNotEmpty(channelId, ProductOrderExcption.class, "渠道id不能为空！");
        //查询渠道信息
        List<Map> channels = commonService.channelById(channelId);
        ValidateUtils.strNotEmpty(channels, ProductOrderExcption.class, "未查询到该生产渠道信息！");
        ValidateUtils.isTrue(channels.size()!=0, ProductOrderExcption.class, "未查询到该生产渠道信息！");
        String channelName = channels.get(0).get("channel_name")==null?"":channels.get(0).get("channel_name").toString();
        Long flowUserId = params.getLong("flowUserId");
        String amountStr = params.getString("amount");
        String remark = params.getString("remark") + "";
        //支行
        String channelSubBranch = params.getString("channelSubBranch");
        //需求金额
        BigDecimal amount = new BigDecimal(amountStr);
        //获取当前登录用户
        UserEntity userEntity = searchUtils.getcurrUser(params);
        //当前登录用户所属部门信息
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());

        Map curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());

        //查询当前所选生产订单
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(scOrderId);
        DggValidateUtil.notNull(productOrder, ProductOrderExcption.class, "没有找到该生产订单！");
        ValidateUtils.isTrue(productOrder.getFlowUserId().equals(userEntity.getId()), ProductOrderExcption.class, "您不是所选生产订单的流程人员，不能进行该操作！");
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02), ProductOrderExcption.class, "订单状态已改变，请刷新后再试！");
        //所有生产订单已完结不能新增产品
        List<String> finishStatus = new ArrayList<>();
        //超期完结
        finishStatus.add(ScProductConstant.RZSCORDER_STATUS19);
        //强制完结
        finishStatus.add(ScProductConstant.RZSCORDER_STATUS20);
        //生产完结
        finishStatus.add(ScProductConstant.RZSCORDER_STATUS17);
        //已退单
        finishStatus.add(ScProductConstant.RZSCORDER_STATUS06);
        //已废单
        finishStatus.add(ScProductConstant.RZSCORDER_STATUS08);
        //已更换产品
//        finishStatus.add(ScProductConstant.RZSCORDER_STATUS21);
        Integer unfinishProOrder = productOrderDao.selectUnfinlishOrder(productOrder.getOrderId(), finishStatus);
        ValidateUtils.isTrue(!unfinishProOrder.equals(0), ProductOrderExcption.class, "销售单下所有生产订单已处于完结/退废单状态,无法新增产品");
        //生产系统新增产品唯一性验证
        boolean res = uniqueOrderUtils.uniqueOrder(params, productOrder.getOrderId(), SystemCommonConstant.PRODUCT_ADD);
        ValidateUtils.isTrue(!res, ProductOrderExcption.class, "所属销售订单下已存在相同产品和渠道的生产单，请重新选择");
        //查询iboss中该订单是否可以新增产品
        boolean ableToAdd = commonService.findFinanceOrderId(productOrder.getOrderId());
        ValidateUtils.isTrue(ableToAdd, ProductOrderExcption.class, "该销售订单不可以新增订单");
        //查询业务类型
        Map busTypeMap = cmsService.getTreeBookObj(typeCode);
        ValidateUtils.strNotEmpty(busTypeMap, ProductOrderExcption.class, "未查询到业务类型信息");

        String businessTypeName = cmsService.getTreeBookName(ScProductConstant.BUS_YT_DK)+"-"+busTypeMap.get("name");
        Map productDetialMap = commonService.getProductInfo(productId);
        ValidateUtils.strNotEmpty(productDetialMap, ProductOrderExcption.class, "未查询到产品信息");
        //查询流程人员数据
        Map flowUser = cmsService.findUser(flowUserId);
        ValidateUtils.strNotEmpty(flowUser, ProductOrderExcption.class, "未查询到所选流程人员");
        String flowUserName = String.valueOf(flowUser.get("realName")) + String.valueOf(flowUser.get("loginName"));
        OrganizationEntity flowUserOrg = organizationManager.findOrgEntityByOrgId(Long.valueOf(flowUser.get("orgId").toString()));


        //获取生产子订单编号
        String scProductOrderNo = cmsService.getBillNumber("sc");
        ValidateUtils.strNotEmpty(scProductOrderNo, ProductOrderExcption.class, "单据号获取失败,请联系管理员！");


        //通过流程id查询流程并将节点更新为第一个节点
        Map nodeFlowIdMap = new HashMap();
        ProductNodeFlow productNodeFlow = null;
        ProductNode productNode = null;
        Long serialId = commonService.getSerialId(productId);
        Long productNodeFlowId = null;
        if(StringUtils.isNotEmpty(productOrder.getNodeJson())){
            Map maps = new HashMap<>();
            maps.put("productId", serialId);
            maps.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            maps.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            productNodeFlow =  apiProductionService.getNodeFlow(maps);
            List<ProductNode> productNodes = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
            if(!CollectionUtils.isEmpty(productNodes)){
                for(ProductNode p :productNodes){
                    if("接单".equals(p.getName())){
                        productNode = p;
                    }
                }
            }
        }else{
            productNodeFlowId = productNodeFlowDao.selectFlowIdByProIdAndBusCode(typeCode, serialId);
            nodeFlowIdMap.put("flowId", productNodeFlowId);
            productNodeFlow = productNodeFlowDao.selectFlowById(nodeFlowIdMap);
            productNode = productNodeDao.queryNodeJd(nodeFlowIdMap);
        }
        ValidateUtils.strNotEmpty(productNodeFlow, CommonExcption.class, "当前流程不存在！");
        ValidateUtils.strNotEmpty(productNode, CommonExcption.class, "当前流程节点不存在！");
        //新增的生产订单
        ProductOrder addProductOrder = BeanUtils.copy(productOrder, ProductOrder.class);
        Date now = new Date();
        long newId = DggKeyWorker.nextId();
        addProductOrder.setId(newId);//主订单id
        this.saveOpt(addProductOrder, userEntity);//保存通用参数
        addProductOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        addProductOrder.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        addProductOrder.setScProductOrderNo(scProductOrderNo);//生产子订单编号
        String newNo = paramsBuildUtils.buildOrderBusinessNo(productOrder.getOrderNo());
        addProductOrder.setOrderBusId(DggKeyWorker.nextId());//销售子订单ID
        addProductOrder.setOrderBusNo(newNo);//售子订单编号
        addProductOrder.setBusinessTypeCode(ScProductConstant.BUS_YT_DK);
        addProductOrder.setBusinessTypeName(businessTypeName);
        addProductOrder.setBusinessProductCode(typeCode);//小业态产品code
        addProductOrder.setBusinessProductName(String.valueOf(busTypeMap.get("name")));//小业态产品名字
        addProductOrder.setProductId(productId); //产品ID
        addProductOrder.setProductName(String.valueOf(productDetialMap.get("name"))); //产品名字
        addProductOrder.setChannelId(channelId); //渠道ID
        addProductOrder.setChannelName(channelName); //渠道名称
        addProductOrder.setSubBranch(channelSubBranch); //支行
        addProductOrder.setLoanAmount(amount);//需求金额
        //接收人改为选择流程人员的部门及当前时间
        addProductOrder.setReceiverId(null);  //接单人id
        addProductOrder.setReceiverName(null);  //接单人名字
        addProductOrder.setReceiverOrgId(null);  //接单人部门ID
        addProductOrder.setReceiverOrgName(null); //接单人部门
        addProductOrder.setReceiveOrderDate(null); //接单时间
        addProductOrder.setReceiveTime(null);
        addProductOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_PRO_ADD);  //订单来源(来源方式)
        addProductOrder.setFlowUserId(flowUserId);  //流程人员ID
        addProductOrder.setFlowUserName(flowUserName);   //流程人员名字
        addProductOrder.setFlowUserOrgId(flowUserOrg.getId());   //流程人员部门ID
        addProductOrder.setFlowUserOrgName(flowUserOrg.getName()); //流程人员部门名字
        addProductOrder.setStatus(ScProductConstant.RZSCORDER_STATUS01);//待接收

        /*addProductOrder.setGoodsId(goodsId);//商品属性ID
        addProductOrder.setGoodsName(goodsName);//商品名称*/
        addProductOrder.setLatestEndUserId(flowUserId); //最新节点更新人ID
        addProductOrder.setLatestEndUserName(flowUserName);  //最新节点更新人名字
        addProductOrder.setLatestEndUserOrgId(flowUserOrg.getId());  //最新节点更新人部门ID
        addProductOrder.setLatestEndNodeId(productNode.getId());  //最新完成节点ID
        addProductOrder.setLatestEndNodeName(productNode.getName());//最新完成节点名字
        addProductOrder.setVersion(productNode.getVersion());//最新完成节点版本
        addProductOrder.setLatestEndNodeTime(now);//最新完成节点时间
        addProductOrder.setLatestEndUserId(null);
        addProductOrder.setLatestEndUserName(null);
        addProductOrder.setLatestEndUserOrgId(null);
        addProductOrder.setLatestEndNodeId(null);
        addProductOrder.setLatestEndNodeName(null);
        addProductOrder.setLatestEndNodeTime(null);
        addProductOrder.setLatestNodeOperatingId(null);
        addProductOrder.setLatestFlowOperatingId(null);
        addProductOrder.setAllotDate(null);
        addProductOrder.setRemark("新增产品，新增原因：" + remark);  //备注
        addProductOrder.setLastRemark("新增产品，新增原因：" + remark);
        addProductOrder.setLastRemarkTime(now);
        //默认值
        //插入流程id
        Map maps = new HashMap<>();
        maps.put("productId", serialId);
        maps.put("businessTypeCode", addProductOrder.getBusinessTypeCode());//一级业态Code
        maps.put("smallBusinessTypeCode", addProductOrder.getBusinessProductCode());// 二级业态Code
        ProductNodeFlow nodeFlow =  apiProductionService.getNodeFlow(maps);
        DggValidateUtil.notNull(nodeFlow, CommonExcption.class, "未查询到["+addProductOrder.getBusinessProductName()+"/"+addProductOrder.getProductName()+"]流程节点的配置信息");
        addProductOrder.setNodeFlowId(nodeFlow.getId());
        addProductOrder.setVersion(nodeFlow.getVersion());
        //接入企大宝任务模板保存json字段
        List<ProductNode> nodeList = apiProductionService.getProductNode(nodeFlow);
        String nodeStr = JSONObject.toJSONString(nodeList);
        addProductOrder.setNodeJson(nodeStr);//设置节点数据
        Long nodeOperatingId = DggKeyWorker.nextId();
        addProductOrder.setLatestNodeOperatingId(nodeOperatingId);  //当前节点操作记录ID
        //保存新增产品生产订单
        productOrderDao.insertSelective(addProductOrder);

        //更新销售子订单josn（表rzsc_order_json）
        this.dealOrderJson(addProductOrder);


        //插入操作记录
        SystemRecord record = new SystemRecord();
        record.setId(DggKeyWorker.nextId());
        record.setSource("2");
        record.setWorkTableName("rzsc_product_order");
        record.setWorkId(addProductOrder.getId());
        record.setWorkNo(addProductOrder.getScProductOrderNo());
        record.setSignOrgId(addProductOrder.getSignOrgId());
        record.setSignOrgName(addProductOrder.getSignOrgName());
        record.setWorkNo(addProductOrder.getScProductOrderNo());
        record.setBeOperaterId(userEntity.getId());
        record.setOperateType("52");
        record.setRemarks("新增产品，新增原因：" + remark);
        record.setOperaterId(userEntity.getOrgId());//操作人员id
        record.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());//操作人员名称
        record.setOperateTime(new Date());//操作时间
        if (org != null) {
            record.setOperaterOrgId(org.getId());
            record.setOperaterOrgName(org.getName());
        } else {
            throw new ProductOrderExcption("未获取到登录用户所在部门信息");
        }
        systemRecordDao.insert(record);
        //插入生产订单超期
        ProductTimeStatus timestatus = new ProductTimeStatus();
        timestatus.setId(addProductOrder.getId());//超期表id和新增主订单id一样
        timestatus.setScProductOrderNo(addProductOrder.getScProductOrderNo());//  //生产子订单编号
        timestatus.setReceiveStartTime(now);  //接收计时开始时间
        timestatus.setReceiveProcessTime(1);  //接收时长
        try {
            timestatus.setReceiveEndTime(DateUtils.dateAddDayJs(now, 1));//接收截至时间
            timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        timestatus.setNodeFlowId(addProductOrder.getNodeFlowId());  //节点流程ID
        timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);  //节点超期状态
        timestatus.setDistributionStartTime(now);    //分配开始时间
        timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);   //订单超期状态
        timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL); //分配超期状态
        timestatus.setFlag(1);//必须要加入

        if (productNodeFlow.getIsnaturalorworkday() == 1) {//工作日
            Date nowDate = new Date();
            String orderEndTime = cmsService.findAfterDate(DateUtil.dateToString(nowDate, "yyyy-MM-dd HH:mm:ss"), productNodeFlow.getManagementCycle()) + " " + DateUtil.dateToString(nowDate, "HH:mm:ss");
            timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime, "yyyy-MM-dd HH:mm:ss"));
        } else {
            try {
                timestatus.setOrderEndTime(DateUtils.dateAddDayJs(now, productNodeFlow.getManagementCycle()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        timestatus.setOrderStartTime(now);
        timestatus.setOrderProcessTime(productNodeFlow.getManagementCycle());
        timestatus.setOrderProcessTimeType(productNodeFlow.getIsnaturalorworkday());
        this.saveOpt(timestatus, userEntity);//设置基础字段

        productTimeStatusDao.insertSelective(timestatus);
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(addProductOrder.getCustomerId());
        customerRecord.setTableName("rzsc_product_order");
        customerRecord.setTableId(addProductOrder.getId());
        customerRecord.setTableNo(addProductOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE6);
        customerRecord.setCreaterId(userEntity.getId());
        customerRecord.setContent(remark);
        MQMessageSendUtil.ucMessageSend(customerRecord);
        //广播新增产品消息
        MQMessageSendUtil.rzMessageSend(1,userEntity,addProductOrder,scOrderId);
        if(SystemCommonConstant.QDS_SC.equals(productOrder.getOrderSource())){
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(addProductOrder,null,userEntity);
        }
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 更改产品
     * @Date 9:43 2019/3/28
     * @Param params 入参集合  origino 来源：RZSC_ORIGINCODE_PRO_ADD，RZSC_ORIGINCODE_PRO_CHANGE，RZSC_ORIGINCODE_AACCEPT_CHANGE
     **/
    @Transactional(rollbackFor = Exception.class)
    public void changeProduct(JSONObject params, String origion) throws IOException {
        this.productChangeParams(params, origion);
        Long scOrderId = params.getLong("id");
        String typeCode = params.getString("typeCode");
        Long productId = params.getLong("productId");
        //Long goodsId = params.getLong("goodsId");
        Long channelId = params.getLong("channelId");
        ValidateUtils.strNotEmpty(channelId, ProductOrderExcption.class, "渠道id不能为空！");
        //查询渠道信息
        List<Map> channels = commonService.channelById(channelId);
        ValidateUtils.strNotEmpty(channels, ProductOrderExcption.class, "未查询到该生产渠道信息！");
        ValidateUtils.isTrue(channels.size()!=0, ProductOrderExcption.class, "未查询到该生产渠道信息！");
        String channelName = channels.get(0).get("channel_name")==null?"":channels.get(0).get("channel_name").toString();
        String remark = params.getString("remark") + "";
        //支行
        String channelSubBranch = params.getString("channelSubBranch");
        //获取当前登录用户
        UserEntity userEntity = searchUtils.getcurrUser(params);
        //当前登录用户所属部门信息
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(userEntity.getOrgId());

        Date now = new Date();

        //现有生产订单
        ProductOrder oldScOrder = productOrderDao.selectByPrimaryKey(scOrderId);
//        ProductNode oldProductNode = productNodeDao.queryNodeJd(new HashMap(1) {{
//            put("flowId", oldScOrder.getNodeFlowId());
//        }});//流程节点
        ProductNode oldProductNode = null;
        logger.info("订单数据>>>>>>>>>："+JSONObject.toJSONString(oldScOrder));
        if(StringUtils.isNotEmpty(oldScOrder.getNodeJson())){
            List<ProductNode> productNodes = JSONArray.parseArray(oldScOrder.getNodeJson(), ProductNode.class);
            logger.info("转换节点数据>>>>>>>>>："+JSONObject.toJSONString(productNodes));
            if(!CollectionUtils.isEmpty(productNodes)){
                for(ProductNode p :productNodes){
                    if("接单".equals(p.getName())){
                        oldProductNode = p;
                    }
                }
            }
        }else{
            oldProductNode = productNodeDao.queryNodeJd(new HashMap(1) {{
                put("flowId", oldScOrder.getNodeFlowId());
            }});//流程节点
        }
        logger.info("获取接单节点>>>>>>>>>："+JSONObject.toJSONString(oldProductNode));
        ValidateUtils.strNotEmpty(oldProductNode, ProductOrderExcption.class, "原节点数据缺失！");
        //查询以前的接单操作记录

        Map oldMap = new HashMap<>();
        oldMap.put("nodeId", oldProductNode.getId());
        oldMap.put("scProductOrderId", oldScOrder.getId());
        ProductNodeOperating oldProNodeOpera = productNodeOperatingDao.selectJDByScOrderIdAndNodeId(oldMap);
        ValidateUtils.strNotEmpty(oldScOrder, ProductOrderExcption.class, "未查询到该生产订单的信息！");
        ValidateUtils.isTrue(oldScOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02)
                || oldScOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS11)
                || oldScOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS01)
                || oldScOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS16), ProductOrderExcption.class, "办理中的订单才能更改产品");
        ValidateUtils.isTrue(!oldScOrder.getIsLoan().equals(1), ProductOrderExcption.class, "该生产订单已放款不可变更产品");
        //生产系统新增产品唯一性验证
        boolean res = uniqueOrderUtils.uniqueOrder(params, oldScOrder.getOrderId(), SystemCommonConstant.PRODUCT_CHANGE);
        ValidateUtils.isTrue(!res, ProductOrderExcption.class, "所属销售订单下已存在相同产品和渠道的生产单，请重新选择");
        //查询业务类型
        Map busTypeMap = cmsService.getTreeBookObj(typeCode);
        ValidateUtils.strNotEmpty(busTypeMap, ProductOrderExcption.class, "未查询到业务类型信息");
        String businessTypeName = cmsService.getTreeBookName(ScProductConstant.BUS_YT_DK)+"-"+busTypeMap.get("name");
        Map productDetialMap = commonService.getProductInfo(productId);
        ValidateUtils.strNotEmpty(productDetialMap, ProductOrderExcption.class, "未查询到产品信息");
        ValidateUtils.isTrue(userEntity.getId().equals(oldScOrder.getFlowUserId()), ProductOrderExcption.class, "您不是所选生产订单的流程人员，不能进行该操作！");


        ProductOrder newProductOrder = this.copyNewBusOrder(oldScOrder, userEntity, org);
//        更新销售子订单josn（表rzsc_order_json）
//        this.dealOrderJson(newProductOrder);

        //通过流程id查询流程并将节点更新为第一个节点

        Map nodeFlowIdMap = new HashMap();
        ProductNodeFlow productNodeFlow = null;
        ProductNode productNode = null;
        Long serialId = commonService.getSerialId(productId);
        Long productNodeFlowId = null;
        List<ProductNode> nodeList = null;
        if(StringUtils.isNotEmpty(oldScOrder.getNodeJson())){
            Map maps = new HashMap<>();
            maps.put("productId", serialId);
            maps.put("businessTypeCode", oldScOrder.getBusinessTypeCode());//一级业态Code
            maps.put("smallBusinessTypeCode", oldScOrder.getBusinessProductCode());// 二级业态Code
            productNodeFlow =  apiProductionService.getNodeFlow(maps);
            nodeList = JSONArray.parseArray(oldScOrder.getNodeJson(), ProductNode.class);
            if(!CollectionUtils.isEmpty(nodeList)){
                for(ProductNode p :nodeList){
                    if("接单".equals(p.getName())){
                        productNode = p;
                    }
                }
            }
        }else{
            productNodeFlowId = productNodeFlowDao.selectFlowIdByProIdAndBusCode(typeCode, serialId);
            nodeFlowIdMap.put("flowId", productNodeFlowId);
            productNodeFlow = productNodeFlowDao.selectFlowById(nodeFlowIdMap);
            productNode = productNodeDao.queryNodeJd(nodeFlowIdMap);
        }
        ValidateUtils.strNotEmpty(productNodeFlow, CommonExcption.class, "当前流程不存在！");
        ValidateUtils.strNotEmpty(productNode, CommonExcption.class, "当前流程节点不存在！");

        //更新现有生产订单产品数据并更改状态为已更改产品
        ProductOrder upScOrder = new ProductOrder();
        this.saveOpt(upScOrder, userEntity);
        if(!CollectionUtils.isEmpty(nodeList)){
            String nodeStr = JSONObject.toJSONString(nodeList);
            upScOrder.setNodeJson(nodeStr);//设置节点数据
        }
        upScOrder.setId(oldScOrder.getId());
        upScOrder.setBusinessProductCode(typeCode);
        upScOrder.setBusinessTypeCode(oldScOrder.getBusinessTypeCode());
        upScOrder.setBusinessTypeName(businessTypeName);
        upScOrder.setBusinessProductName(String.valueOf(busTypeMap.get("name")));
        upScOrder.setProductId(productId);
        upScOrder.setProductName(String.valueOf(productDetialMap.get("name")));
        upScOrder.setOrderId(oldScOrder.getOrderId());
        upScOrder.setOrderNo(oldScOrder.getOrderNo());
        upScOrder.setOrderBusId(oldScOrder.getOrderBusId());
        upScOrder.setOrderBusNo(oldScOrder.getOrderBusNo());
        upScOrder.setStatus(oldScOrder.getStatus());
        upScOrder.setReceiveTime(oldScOrder.getReceiveTime());
       /* upScOrder.setGoodsId(goodsId);
        upScOrder.setGoodsName(goodsName);*/
        upScOrder.setChannelId(channelId);
        upScOrder.setChannelName(channelName);
        upScOrder.setNodeFlowId(productNodeFlowId);//节点流程id
        upScOrder.setLatestEndNodeId(productNode.getId());
        upScOrder.setLatestEndNodeName(productNode.getName());
        upScOrder.setLatestEndUserId(userEntity.getId()); //最新节点更新人ID
        upScOrder.setLatestEndUserName(userEntity.getRealName() + userEntity.getLoginName());  //最新节点更新人名字
        upScOrder.setLatestEndUserOrgId(userEntity.getOrgId());  //最新节点更新人部门ID
        upScOrder.setLatestEndNodeId(productNode.getId());  //最新完成节点ID
        upScOrder.setLatestEndNodeName(productNode.getName());//最新完成节点名字
        upScOrder.setLatestEndNodeTime(now);//最新完成节点时间
        upScOrder.setVersion(productNode.getVersion());
        upScOrder.setLastRemarkTime(now);
        upScOrder.setVersion(productNode.getVersion());
        upScOrder.setSubBranch(channelSubBranch);
        upScOrder.setMoney(oldScOrder.getMoney());


        if (origion.equals(ScProductConstant.RZSC_ORIGINCODE_AACCEPT_CHANGE)) {
            upScOrder.setStatus(ScProductConstant.RZSCORDER_STATUS02);
            upScOrder.setReceiveTime(now);
            upScOrder.setReceiverId(userEntity.getId());
            upScOrder.setReceiverOrgId(userEntity.getOrgId());
            upScOrder.setReceiverOrgName(org.getName());
            upScOrder.setReceiveOrderDate(now);
            upScOrder.setLastRemark("接收订单时更改产品,原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName());
            upScOrder.setRemark("接收订单时更改产品,原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName());
        } else {
            upScOrder.setLastRemark("更换产品,原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName() + ",更换原因为:" + remark);
            upScOrder.setRemark("更换产品,原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName() + ",更换原因为:" + remark);
        }

        productOrderDao.updateByPrimaryKeySelective(upScOrder);
        //复制产品超期记录表数据
        ProductTimeStatus productTimeStatus = productTimeStatusDao.selectByPrimaryKey(oldScOrder.getId());


        if (productTimeStatus == null) {
            productTimeStatus = productTimeStatusService.insertProductStatus(oldScOrder);
        }
        productTimeStatus.setNodeFlowId(productNodeFlowId);
        List<ProductNode> productNodes = new ArrayList<ProductNode>();
        if(net.dgg.rz.common.utils.StringUtils.isNotEmpty(oldScOrder.getNodeJson())){
            productNodes = JSONArray.parseArray(oldScOrder.getNodeJson(), ProductNode.class);
        }else{
            Map map = new HashMap(2);
            map.put("flowId", productNodeFlow.getId());
            map.put("version",productNode.getVersion());
            productNodes = productNodeDao.queryByFlowIdAndVersion(map);
        }
        if (null == oldProNodeOpera) {
            //更新记录id
            Long operatingId = DggKeyWorker.nextId();
            //节点更新记录表实体
            ProductNodeOperating operating = new ProductNodeOperating();
            operating.setId(operatingId);
            operating.setScProductOrderId(oldScOrder.getId());
            operating.setScProductOrderNo(oldScOrder.getScProductOrderNo());
            operating.setFlowUserId(userEntity.getId());
            operating.setFlowUserName(userEntity.getRealName() + userEntity.getLoginName());
            operating.setFlowOrgId(userEntity.getOrgId());
            operating.setFlowOrgName(org.getName());
            operating.setOrderStatus(oldScOrder.getStatus());
            operating.setNodeId(productNode.getId());
            operating.setNodeName(productNode.getName());
            operating.setNodeProcessTime(productNode.getHandleDate());
            operating.setNodeProcessTimeType(productNode.getIsNaturalorWorkday().toString());
            operating.setRemarksType(1);
            operating.setRemark(userEntity.getRealName() + userEntity.getLoginName() + "接收订单");
            operating.setNodeProcessTimeType(productNodeFlow.getIsnaturalorworkday() == null ? null : productNodeFlow.getIsnaturalorworkday().toString());
            operating.setNodeOpetateTime(now);
            operating.setCreateUser(userEntity);
            operating.setCreateTime(now);
            operating.setCreaterOrgName(org.getName());
            if (null != productTimeStatus && null != productTimeStatus.getReceiveEndTime()) {
                int i = DateUtils.compare_date(new Date(), productTimeStatus.getReceiveEndTime());
                if (i >= 1) {
                    productTimeStatus.setReceiveTimeStatus(ScProductConstant.TIME_OUT);
                    operating.setNodeTimeStatus(ScProductConstant.TIME_OUT);
                    operating.setNodeStartTime(productTimeStatus.getReceiveStartTime());
                    operating.setNodeEndTime(productTimeStatus.getReceiveEndTime());
                    String date = DateUtils.transTime(productTimeStatus.getReceiveEndTime(), new Date());
                    operating.setNodeOverdueTime(date);
                    flowNodeService.nodePunish(operating, oldScOrder, productNode);
                } else {
                    productTimeStatus.setReceiveTimeStatus(productTimeStatus.getReceiveTimeStatus());
                    operating.setNodeTimeStatus(ScProductConstant.NORMAL);
                    operating.setNodeStartTime(productTimeStatus.getReceiveStartTime());
                    operating.setNodeEndTime(productTimeStatus.getReceiveEndTime());
                }
        }
            productNodeOperatingDao.insertSelective(operating);
        }else {
            Long nodeId = productNode.getId();
            oldProNodeOpera.setNodeId(nodeId);
            productNodeOperatingDao.updateByPrimaryKeySelective(oldProNodeOpera);
        }

        //默认的下一节点计划更新时间
        productTimeStatus.setNodeStartTime(now);
        //节点截止时间计算
        Date currentDate = commonService.getDateFromStartByType(now,
                productNodes.get(1).getHandleDate(), 0L,
                productNodes.get(1).getIsNaturalorWorkday());
        productTimeStatus.setNodeEndTime(currentDate);
        productTimeStatus.setNodeId(productNodes.get(1).getId());
        productTimeStatus.setNodeName(productNodes.get(1).getName());
        productTimeStatus.setNodeProcessTime(productNodes.get(1).getHandleDate());
        productTimeStatus.setNodeProcessTimeType(productNodes.get(1).getIsNaturalorWorkday());
        productTimeStatus.setNodeTimeStatus(ScProductConstant.NORMAL);

        productTimeStatusDao.updateByPrimaryKeySelective(productTimeStatus);


        //新增的操作记录
        SystemRecord record = new SystemRecord();
        record.setId(DggKeyWorker.nextId());
        record.setSource("2");
        record.setWorkTableName("rzsc_product_order");
        record.setWorkId(upScOrder.getId());
        record.setWorkNo(upScOrder.getScProductOrderNo());
        record.setSignOrgId(upScOrder.getSignOrgId());
        record.setSignOrgName(upScOrder.getSignOrgName());
        record.setWorkNo(upScOrder.getScProductOrderNo());
        record.setBeOperaterId(userEntity.getId());
        record.setOperateType("53");
        if (origion.equals(ScProductConstant.RZSC_ORIGINCODE_AACCEPT_CHANGE)) {
            record.setRemarks("接收订单时更改产品,原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName() + "-" + oldScOrder.getChannelName());
        } else {
            record.setRemarks("更改产品，更改原因：" + remark + "。原产品为" + oldScOrder.getBusinessProductName() + "-" + oldScOrder.getProductName()
                    + "-" + oldScOrder.getGoodsName() + "-" + oldScOrder.getChannelName());
        }
        record.setOperaterId(userEntity.getOrgId());//操作人员id
        record.setOperaterName(userEntity.getRealName() + userEntity.getLoginName());//操作人员名称
        record.setOperateTime(now);//操作时间
        record.setOperaterOrgId(org.getId());
        record.setOperaterOrgName(org.getName());
        systemRecordDao.insert(record);
        if(0 == oldScOrder.getIsJdSms()){
            Map contentParamMap = new HashMap();
            contentParamMap.put("orderNo",oldScOrder.getOrderNo());
            TreeBook treeBook = null;
            try{
                treeBook = treeBookService.getTreeBookByCode("RZSC_MESSAGE_TEMPLATE_JD");
            }catch (Exception e){
                logger.error("查询短信模板id数据字典失败：",e.toString());
            }
            Map resultMap = commonService.sendSMS(desUtil.decrypt(oldScOrder.getCustomerPhone()), net.dgg.rz.common.utils.StringUtils.isNotEmpty(treeBook)?treeBook.getExt1():"", contentParamMap, "接单触发", 1);
            if(10000 == Long.valueOf(resultMap.get("code").toString())){
                productOrderDao.updateSendSms(oldScOrder.getOrderNo());
            }else {
                logger.error(resultMap.toString());
            }
        }
        //通过MQ推送消息到UC
        CustomerRecord customerRecord = new CustomerRecord();
        customerRecord.setCustomerId(upScOrder.getCustomerId());
        customerRecord.setTableName("rzsc_product_order");
        customerRecord.setTableId(upScOrder.getId());
        customerRecord.setTableNo(upScOrder.getScProductOrderNo());
        customerRecord.setRemarkType(ScNoteType.RZSC_NOTE_CODE7);
        customerRecord.setCreaterId(userEntity.getId());
        customerRecord.setContent(remark);
        MQMessageSendUtil.ucMessageSend(customerRecord);
        //广播新增产品消息
        MQMessageSendUtil.rzMessageSend(2,userEntity,upScOrder,scOrderId);
        if(SystemCommonConstant.QDS_SC.equals(oldScOrder.getOrderSource())){
            //同步生产单状态给企大宝
            MQMessageSendUtil.qdsMessageSend(upScOrder,null,userEntity);
        }
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 新增/更改产品入参验证
     * @Date 17:01 2019/3/27
     * @Param
     **/
    public void productChangeParams(JSONObject params, String type) {
        DggValidateUtil.notNull(params, ProductOrderExcption.class, "参数为空！");
        DggValidateUtil.notNull(params.getLong("id"), ProductOrderExcption.class, "生产订单id为空！");
        DggValidateUtil.notNull(params.getString("typeCode"), ProductOrderExcption.class, "业务code为空！");
        DggValidateUtil.notNull(params.getLong("productId"), ProductOrderExcption.class, "产品id为空！");
        //DggValidateUtil.notNull(params.getLong("goodsId"), ProductOrderExcption.class, "商品属性id为空！");
        DggValidateUtil.notNull(params.getLong("channelId"), ProductOrderExcption.class, "渠道id为空！");
        String channelSubBranch = params.getString("channelSubBranch");
        if (null != channelSubBranch) {
            ValidateUtils.isTrue(channelSubBranch.length() <= 50, ProductOrderExcption.class, "支行信息最多50个字!");
        }
        if (type.equals(ScProductConstant.RZSC_ORIGINCODE_PRO_ADD)) {
            DggValidateUtil.notNull(params.getLong("flowUserId"), ProductOrderExcption.class, "流程人员id为空！");
            DggValidateUtil.notNull(params.getString("amount"), ProductOrderExcption.class, "需求金额为空！");
        }
        if (!type.equals(ScProductConstant.RZSC_ORIGINCODE_AACCEPT_CHANGE)) {
            String remark = params.getString("remark");
            if (null != remark) {
                ValidateUtils.isTrue(remark.length() <= 500, ProductOrderExcption.class, "备注内容必须小于500个字!");
            }
        }

    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 复制生产单所有数据（数据复制后对应id，生产单id，编号等对应更改）
     * @Date 9:47 2019/3/29
     * @Param
     **/

    @Transactional(rollbackFor = Exception.class)
    public ProductOrder copyNewBusOrder(ProductOrder oldScOrder, UserEntity userEntity, OrganizationEntity org) throws IOException {

        //获取生产子订单编号
        Long scOrderId = DggKeyWorker.nextId();

        //复制作废生产订单
        ProductOrder newProductOrder = BeanUtils.copy(oldScOrder, ProductOrder.class);
        newProductOrder.setId(scOrderId);
        newProductOrder.setRemark("该订单已更换产品");
        newProductOrder.setFlag(1);
        this.saveOpt(newProductOrder, userEntity);
        productOrderDao.insertSelective(newProductOrder);


        return newProductOrder;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 销售子订单数据处理
     * @Date 10:40 2019/4/2
     * @Param oldOrder原生产订单 newScOrder type操作类型
     **/
    @Transactional
    public void dealOrderJson(ProductOrder newScOrder) {
        OrderJson orderJson = orderJsonDao.selectByOrderId(newScOrder.getOrderId());
        ValidateUtils.strNotEmpty(orderJson, ProductOrderExcption.class, "没有查询到销售订单数据");
        String busOrderStr = orderJson.getOrderBusinessJson();
        List<OrderBusJsonDto> orderBusJsonDtos = JsonUtil.json2List(busOrderStr, OrderBusJsonDto.class);
//            兼容老数据不加入数据验证
//          List<ProductOrder> productOrders = productOrderDao.getListByOrderId(newScOrder.getOrderId(), null, null);
        OrderBusJsonDto orderBusJsonDto = new OrderBusJsonDto();
        orderBusJsonDto.setOrderBusId(String.valueOf(newScOrder.getOrderBusId()));
        orderBusJsonDto.setOrderBusNo(newScOrder.getOrderBusNo());
        orderBusJsonDto.setProductOrgId(String.valueOf(newScOrder.getProductOrgId()));
        orderBusJsonDto.setProductOrgName(newScOrder.getProductOrgName());
        orderBusJsonDto.setBusinessTypeCode(newScOrder.getBusinessTypeCode());
        orderBusJsonDto.setBusinessTypeName(newScOrder.getBusinessTypeName());
        orderBusJsonDto.setBusinessProductCode(newScOrder.getBusinessProductCode());
        orderBusJsonDto.setBusinessProductName(newScOrder.getBusinessProductName());
        orderBusJsonDto.setProductId(String.valueOf(newScOrder.getProductId()));
        orderBusJsonDto.setProductName(newScOrder.getProductName());
        orderBusJsonDto.setContractNo(newScOrder.getContractNo());
        orderBusJsonDto.setProductGoodsId(String.valueOf(newScOrder.getGoodsId()));
        orderBusJsonDto.setProductAttr(newScOrder.getGoodsName());
        orderBusJsonDto.setServiceCharge(String.valueOf(newScOrder.getServiceCharge()));
        orderBusJsonDto.setRateType(newScOrder.getRateType());
        orderBusJsonDto.setLoanAmount(String.valueOf(newScOrder.getLoanAmount()));
        orderBusJsonDto.setChannelId(String.valueOf(newScOrder.getChannelId()));
        orderBusJsonDto.setFlowUserId(String.valueOf(newScOrder.getFlowUserId()));
        orderBusJsonDto.setChannelName(newScOrder.getChannelName());
        orderBusJsonDto.setAmount(String.valueOf(newScOrder.getMoney()));
        if(orderBusJsonDtos==null){
            orderBusJsonDtos = new ArrayList<>();
        }
        orderBusJsonDtos.add(orderBusJsonDto);
        String orderbusJson = JSONObject.toJSONString(orderBusJsonDtos);
        OrderJson orderJsonUp = new OrderJson();
        orderJsonUp.setId(orderJson.getId());
        orderJsonUp.setOrderBusinessJson(orderbusJson);
        orderJsonDao.updateByPrimaryKeySelective(orderJsonUp);
    }


    /**
     * @return productOrderDtos
     * @Author chenyang
     * @Description APP待接收页面数据接口
     * @Date 10:40 2019/4/8
     * @Param
     **/
    public List<ProductOrderDto> waitReceivedOrderWithPage(Map<String, Object> params) {

        List<String> statusAttr = new ArrayList<>();
        String target = params.get("target").toString();
        switch (target) {
            case "0":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                params.put("statusArr", statusAttr);
                break;
            case "1":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                params.put("statusArr", statusAttr);
            case "2":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                params.put("statusArr", statusAttr);
                break;
            default:
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS16);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS11);
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS01);
                params.put("statusArr", statusAttr);
                break;
        }
        //数据权限参数注入
        dataPermissionUtils.auditorDataAccess(params);
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "当前未登录，请登录后重试");
        params.put("flowUser", userEntity.getId());
        //入参操作
        searchUtils.paramsOperateApp(params);
        List<ProductOrderDto> productOrderDtos = productOrderDao.scOrderWithPage(params);
        //翻译字段
        String[] transColum = {"originCode", "status"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }

    /**
     * APP待审核 分页查询生产订单列表数据
     */
    public List<ProductOrderDto> auditOrderAppWithPage(Map params) {
        List<String> statusAttr = new ArrayList<>();

        String target = String.valueOf(params.get("target"));
        switch (target) {
            case "0":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS05);
                params.put("statusArr", statusAttr);
                break;
            case "1":
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS07);
                params.put("statusArr", statusAttr);
                break;
            default:
                statusAttr.add(ScProductConstant.RZSCORDER_STATUS05);
                params.put("statusArr", statusAttr);
                break;
        }


        //数据权限参数注入
        dataPermissionUtils.auditorDataAccess(params);
        UserEntity userEntity = searchUtils.getcurrUser(params);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "当前未登录，请登录后重试");
        params.put("flowUser", userEntity.getId());
        //入参操作
        searchUtils.paramsOperateApp(params);
        List<ProductOrderDto> productOrderDtos = productOrderDao.scOrderForAuditWithPage(params);

        //翻译字段
        String[] transColum = {"originCode", "status"};
        productOrderDtos = translateUtil.translateList(transColum, productOrderDtos);
        System.out.println();
        //隐藏字段
        String[] hideColum = {"customerPhone"};
        productOrderDtos = desUtil.decryptList(hideColum, productOrderDtos);
        productOrderDtos = CustomerNumberEncryptionUtil.encryptionList(hideColum, productOrderDtos);
        return productOrderDtos;
    }

    /**
     * APP 融资生产详情
     */
    public Map<String, Object> findOrderDetail(Long productOrderId, String userLoginName) {
        Map<String, Object> resultData = new HashMap<>();
        Map<String, Object> customerInfo = new HashMap<>();
        Map<String, Object> productOrderInfo = new HashMap<>();

        Map<String, Object> businessInfo = new HashMap<>();

        Map<String, Object> basicInfo = new HashMap<>();
        Map<String, Object> bottomSheet = new HashMap<>();
        Map<String, Object> lendingInfo = new HashMap<>();

        ValidateUtils.strNotEmpty(productOrderId, CommonExcption.class, "生产子订单id不能为空");
        //订单信息
        ProductOrderDto order = productOrderDao.selectDtoByPrimaryKey(productOrderId);
        ValidateUtils.strNotEmpty(order, CommonExcption.class, "找不到该订单号订单！");
        OrderJson orderJson = orderJsonDao.selectByOrderId(order.getOrderId());
        order.setStatus(translateUtil.translateCode(order.getStatus()));//翻译状态
        order.setOriginCode(translateUtil.translateCode(order.getOriginCode()));//翻译订单来源方式
        order.setWayOfLoanName(ModuleCodeConstant.paymentMethod.get(order.getWayOfLoan()));

        //order.setWayOfLoanName(translateUtil.translateCode(order.getWayOfLoan()));//还款方式翻译
        String[] hideColum = {"customerPhone"};//隐藏
        order.setCustomerPhone(desUtil.decrypt(order.getCustomerPhone()));//解密电话号码
        order = CustomerNumberEncryptionUtil.encryptionObject(hideColum, order);//隐藏电话号码
        //客户信息
        customerInfo.put("customerName", order.getCustomerName());     //客户名称
        customerInfo.put("customerPhone", order.getCustomerPhone());   //客户电话
        //流程信息
        List<Map> flowInfo = productNodeService.queryNodeListByProductOrderId(productOrderId, order.getNodeFlowId(), order.getVersion());

        //生产订单信息
        productOrderInfo.put("businessProductName", order.getBusinessProductName()); //业务
        productOrderInfo.put("productName", order.getProductName());                 //产品
        productOrderInfo.put("channelName", order.getChannelName());                 //渠道
        productOrderInfo.put("receiveOrderDate", order.getReceiveOrderDate());       //接单时间
        productOrderInfo.put("contractNo", order.getContractNo());                   //合同编号
        productOrderInfo.put("orderNo", order.getOrderNo());                         //订单编号
        productOrderInfo.put("latestEndNodeName", order.getLatestEndNodeName());     //当前流程节点
        productOrderInfo.put("flowUserName", order.getFlowUserName());               //流程人员
        productOrderInfo.put("scProductOrderNo", order.getScProductOrderNo());       //生产订单编号
        productOrderInfo.put("goodsName", order.getGoodsName());                      //商品属性
        productOrderInfo.put("loanAmount", order.getLoanAmount());                    //商品属性
        productOrderInfo.put("flowUserOrgName",order.getFlowUserOrgName());           //流程人员部门名称
        //借贷人信息
        List<OrderContact> orderContactList = orderContactDao.getListByOrderNo(order.getOrderNo());
        if (orderContactList != null && orderContactList.size() > 0) {
            for (OrderContact orderContact : orderContactList) {
                if (net.dgg.rz.common.utils.StringUtils.isNotEmpty(orderContact.getCardId())) {
                    orderContact.setCardId(IdCardUtil.hiddenIdCard(orderContact.getCardId()));
                }
            }
            String[] transColum = {"contactMaritalStatus", "relationshipOfCus"};
            orderContactList = translateUtil.translateList(transColum, orderContactList);
            String[] hideColums = {"no"};                                                   //隐藏
            orderContactList = desUtil.decryptList(hideColums, orderContactList);
            orderContactList = CustomerNumberEncryptionUtil.encryptionList(hideColums, orderContactList);
            //borrowLoanInfo.put("orderContactList",orderContactList);
        }
        //申请审核记录
        Map params = new HashMap();
        params.put("workId", order.getId());
        params.put("scProductOrderId", order.getId());
        int[] operateTypeArr = {6, 11, 28, 29, 30, 31};//6、退单 11、废单 28、退单审核通过 29、退单审核驳回 30、废单审核通过 31、废单审核驳回
        params.put("operateTypeArr", operateTypeArr);
        List<SystemRecord> systemRecords = systemRecordDao.findByParamsList(params);
        if (systemRecords != null && systemRecords.size() > 0) {
            for (SystemRecord systemRecord : systemRecords) {
                systemRecord.setOperateType(SystemRecord.operateTypeMap.get(systemRecord.getOperateType()));
            }
            basicInfo.put("auditLogs", systemRecords);
        }
        //备注信息列表
        List<ProductNodeOperating> allRemarksList = productNodeOperatingDao.queryProductOperatingWithPage(params);

        businessInfo.put("businessProductName", order.getBusinessProductName());  //业务
        businessInfo.put("productName", order.getProductName());                  //产品
        businessInfo.put("goodsName", order.getGoodsName());                      //商品名称
        businessInfo.put("channelName", order.getChannelName());                  //渠道
        businessInfo.put("subBranch", order.getSubBranch());                      //支行
        businessInfo.put("contractNo", order.getContractNo());                    //合同编号
        businessInfo.put("loanAmount", order.getLoanAmount());                     //需求金额
        businessInfo.put("rateType", translateUtil.translateCode(orderJson.getLoansRateType()));                    //利息方式
        businessInfo.put("interest", orderJson.getLoansInterest());                    //贷款利息
        businessInfo.put("loanNum", orderJson.getLoansNum());                      //贷款年限
        //放款信息
        lendingInfo.put("loanMoney",order.getLoanMoney());                           //放款金额
        lendingInfo.put("loanTime",order.getLoanTime());                             //放款时间
        lendingInfo.put("loanTimeDay",order.getLoanTimeDay());                       //放款时长
        lendingInfo.put("wayOfLoanName",order.getWayOfLoanName());                   //还款方式
        lendingInfo.put("repaymentDate",order.getRepaymentDate());                  //还款到期时间
        lendingInfo.put("installmentRepayment",order.getInstallmentRepayment());     //每期还款金额
        lendingInfo.put("dateOfLoan",order.getDateOfLoan());                         //每期还款时间

        basicInfo.put("flowInfo", flowInfo);
        basicInfo.put("customerInfo", customerInfo);
        basicInfo.put("productOrderInfo", productOrderInfo);
        basicInfo.put("lendingInfo",lendingInfo);
        bottomSheet.put("borrowLoanInfo", orderContactList);
        bottomSheet.put("businessInfo", businessInfo);

        resultData.put("basicInfo", basicInfo);
        resultData.put("bottomSheet", bottomSheet);
        resultData.put("remarksNote", allRemarksList);
        return resultData;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO APP更新节点页面数据
     * @Date 17:31 2019/4/15
     * @Param
     **/

    public Map queryDataForUpNode(Long scOrderId, String nodeId, String userLoginName) {
        //验证当前用户是否可以操作该主订单
        this.validationUpdateNode(scOrderId, "openUpdateNode", userLoginName);

        //主订单
        ProductOrder productOrder = this.selectByPrimaryKey(scOrderId);
        ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02), ProductOrderExcption.class
                , "此订单当前状态不是办理中不能操作该订单，请刷新列表！");
        //查节点
        List<ProductNode> proNodes = new ArrayList<>();
        Map mapNode = new HashMap();
        List<ProductNode> nodelist = new ArrayList<ProductNode>();
        if(StringUtils.isNotEmpty(productOrder.getNodeJson())){
            //直接拉取订单里面记录的节点数据
            nodelist = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
        }else{
            mapNode.put("flowId", String.valueOf(productOrder.getNodeFlowId()));
            mapNode.put("version", productOrder.getVersion());
            ProductNodeFlow productNodeFlow= productNodeFlowDao.selectFlowById(mapNode);
            Integer old = productNodeFlow.getIsOld();
            if (old==null||old.equals(0)) {
                nodelist = flowNodeService.queryByFlowId(mapNode);
            }else {
                nodelist= flowNodeService.queryByFlowIdAndVersion(mapNode);
            }
        }
        if (nodelist == null || nodelist.size() < 1) {
            throw new FlowNodeExcption("主订单的流程下未查询到节点");
        }
        //组装返回数据格式
        for (ProductNode scProductNode : nodelist) {
            List<Map<String, Object>> relationFieldMapList = new ArrayList<>();
            String relationFieldIds = scProductNode.getRelationFieldIds();
            if (StringUtils.isNotBlank(relationFieldIds)) {
                if (relationFieldIds.contains(",")) {
                    String[] relationFieldSplits = relationFieldIds.split(",");
                    for (String relationFieldSplit : relationFieldSplits) {
                        Map<String, Object> dataMap = new HashMap<>();
                        //如果是还款时间，sort为16，特殊处理
                        if ("16".equals(relationFieldSplit)) {
                            relationFieldMapList.add(new HashMap<String,Object>(){{
                                put("sort", "16");
                                put("name", "还款类型");
                            }});
                        }else {
                            dataMap.put("sort",relationFieldSplit);
                            dataMap.put("name", ModuleCodeConstant.relationField.get(relationFieldSplit));
                            relationFieldMapList.add(dataMap);
                        }
                    }
                } else {
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("sort",relationFieldIds);
                    dataMap.put("name", ModuleCodeConstant.relationField.get(relationFieldIds));
                    relationFieldMapList.add(dataMap);
                }
                scProductNode.setRelationFieldMapList(relationFieldMapList);
            }

            if (null != scProductNode.getName() && !"".equals(scProductNode.getName()) && !"接单".equals(scProductNode.getName())) {
                proNodes.add(scProductNode);//设置传递到页面的节点
            }
        }
        //当未选择则节点则默认下一节点
        int sort = 1;
        Integer nodelistSize = nodelist.size();
        if (productOrder.getLatestEndNodeId() != null && nodeId == null) {
            for (ProductNode scProductNode : nodelist) {
                if(scProductNode.getId().equals(productOrder.getLatestEndNodeId())){
                    sort = scProductNode.getSort()+1;
                    break;
                }
            }
            if(sort<=nodelistSize){
                for (ProductNode scProductNode : nodelist) {
                    if(sort==scProductNode.getSort().intValue()){
                        nodeId = scProductNode.getId().toString();
                        break;
                    }
                }
            }
        }

        Map map = new HashMap();
        map.put("nodelist", proNodes);//添加的流程节点
        map.put("productOrder", productOrder);//主订单
        map.put("code", productOrder.getBusinessTypeCode());//业态标识code
        map.put("nodeId", nodeId);//所选择的节点，如果未选择则默认下一节点
        map.put("refundType", ModuleCodeConstant.paymentMethodList);//
        return map;
    }


    /**
     * @return 0为老数据，1为新数据
     * @Author Quanlin Wan
     * @Description //TODO 验证订单是老流程还是新流程（4月22日兼容老数据，绕过更换产品）
     * @Date 8:57 2019/4/23
     * @Param
     **/
    public Integer verifyOld(String scOrderId) {
        ValidateUtils.strNotEmpty(scOrderId, ProductOrderExcption.class, "生产订单id为空");
        ProductOrder productOrder = this.selectByPrimaryKey(Long.valueOf(scOrderId));
        ValidateUtils.strNotEmpty(productOrder.getNodeFlowId(), ProductOrderExcption.class,"未查询到流程节点信息" );
        Integer verifyOld = null;
        if(StringUtils.isNotEmpty(productOrder.getNodeJson())){
            verifyOld = 1;
        }else{
            ProductNodeFlow productNodeFlow=productNodeFlowDao.selectFlowById(new HashMap(1){{
                put("flowId", productOrder.getNodeFlowId());
            }});
            ValidateUtils.strNotEmpty(productNodeFlow, ProductOrderExcption.class,"未查询到流程节点信息" );
            verifyOld = productNodeFlow.getIsOld();
            //将异常数据处理为老流程
            if (verifyOld !=1||ScProductConstant.RZSCORDER_STATUS11.equals(productOrder.getStatus())||ScProductConstant.RZSCORDER_STATUS16.equals(productOrder.getStatus())) {
                verifyOld=0;
            }
        }
        return verifyOld;
    }
    /**
     * @return
     * @Description 跟进中统计报表统计部分
     * @Author chenyang
     **/
    public Map<String, Object>  findMortgageLoanCount(Map<String, Object> params){
        Map<String, Object> data = new HashMap<>();
        data.putAll(params);
        dataPermissionUtils.flowUserDataAccessReport(params, ModuleCodeConstant.RZSC_STATISTICAL_CODE);
        Map<String, Object> mortgageLoanCount = productOrderDao.findMortgageLoanCount(data);
        Map<String, Object> c = productOrderDao.countMortgageList(data);
        if (null != c) {
            mortgageLoanCount.putAll(c);
        }
        return mortgageLoanCount;
    }

    /**
     * @return
     * @Description 跟进中统计报表列表部分
     * @Author chenyang
     **/
    public Map<String, Object> findCreditLoanCount(Map<String, Object> params){
        Map<String, Object> data = new HashMap<>();
        data.putAll(params);
        dataPermissionUtils.flowUserDataAccessReport(params, ModuleCodeConstant.RZSC_STATISTICAL_CODE);
        Map<String, Object> creditLoanCount = productOrderDao.findCreditLoanCount(data);
        Map<String, Object> creditList = productOrderDao.countCreditList(data);
        if (null != creditList) {
            creditLoanCount.putAll(creditList);
        }
        return creditLoanCount;
    }

    /**
     * @return
     * @Description 跟进中统计报表列表部分
     * @Author chenyang
     **/
    public Map<String, Object> findCapitalBusinessCount(Map<String, Object> params){
        Map<String, Object> data = new HashMap<>();
        data.putAll(params);
        dataPermissionUtils.flowUserDataAccessReport(params, ModuleCodeConstant.RZSC_STATISTICAL_CODE);
        Map<String, Object> capitalBusinessCount = productOrderDao.findCapitalBusinessCount(data);
        return capitalBusinessCount;
    }

    /**
     * @return
     * @Description 后台上传汇总报表
     * @Author chenyang
     **/
    public Map<String, Object> findBackGroundReportCount(Map<String, Object> params){
        Map<String, Object> data = new HashMap<>();
        data.putAll(params);
        dataPermissionUtils.flowUserDataAccessReport(data, ModuleCodeConstant.RZSC_STATISTICAL_CODE);
        Map<String, Object> backGroundReportCount = productOrderDao.findBackGroundReportCount(data);
        return backGroundReportCount;
    }
    /**
     * @return
     * @Description 跟进中统计报表列表部分
     * @Author chenyang
     **/
    public List<Map<String, Object>> getFollowUpReportWithPage(Map<String, Object> params){
        Map<String, Object> data = new HashMap<>();
        data.putAll(params);
        UserEntity userEntity = searchUtils.getcurrUser(data);
        ValidateUtils.strNotEmpty(userEntity, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        //最终返回数据
        List<Map<String, Object>> finalData = new ArrayList<>();
        //查询统计列表数据
        dataPermissionUtils.flowUserDataAccess(data, ModuleCodeConstant.RZSC_STATISTICAL_CODE);
        searchUtils.paramsOperate(data);
        List<Map<String, Object>> resultDatas = productOrderDao.getFollowUpReportWithPage(data);
        params.put("count", data.get("count"));
        //组装统计数据
        if(resultDatas!=null&&resultDatas.size()>0){
            for (Map<String, Object> resultData : resultDatas) {
                Object flowUserId = resultData.get("flowUserId");//流程人员ID
                Object flowUserOrgId = resultData.get("flowUserOrgId");//流程人员部门ID
                Object productOrgId = resultData.get("productOrgId");//生产所属ID
                params.put("flowUserId", flowUserId);
                params.put("flowUserOrgId", flowUserOrgId);
                params.put("productOrgId", productOrgId);
                Map<String, Object> countMap = null;
                int businessName = Integer.parseInt(params.get("businessName").toString());
                switch (businessName) {
                    case 1:
                        countMap = this.findMortgageLoanCount(params);
                        break;
                    case 2:
                        countMap = this.findCreditLoanCount(params);
                        break;
                    case 3:
                        countMap = this.findCapitalBusinessCount(params);
                        break;
                    case 4:
                        countMap = this.findBackGroundReportCount(params);
                        break;
                    default:
                        break;
                }
                resultData.putAll(countMap);
                finalData.add(resultData);
            }
        }
        return finalData;
    }

    /**
     * 痛通过客户id查询生产单（带有数据权限）
     * @param params
     * @return
     */
    public List<ProductOrderDto> findScorderByCustomerId(Map params) {
        //参数注入
        searchUtils.paramsComplete(params);
        //数据权限注入
        dataPermissionUtils.flowUserDataAccess(params, ModuleCodeConstant.RZSC_COMPLETE_CUSTOMER_CODE);
        return productOrderDao.findScorderByCustomerId(params);
    }
    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 查询生产单是否需要下一审核人
     * @Date 19:02 2019/4/22
     * @Param id生产订单id
     **/
    public Integer needNextAuditor(Long id) {
        ProductOrder productOrder= this.selectByPrimaryKey(Long.valueOf(id));
        Map map = new HashMap();
        ProductNodeFlow nodeFlow = null;
        Long serialId = commonService.getSerialId(productOrder.getProductId());
        if(net.dgg.rz.common.utils.StringUtils.isNotEmpty(productOrder.getNodeJson())){
            map.put("productId", serialId);
            map.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            map.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            nodeFlow = apiProductionService.getNodeFlow(map);
        }else{
            map.put("flowId", productOrder.getNodeFlowId());
            nodeFlow = flowNodeService.findFlowById(map);
        }
        Integer examineGrade = nodeFlow.getExamineGrade() == null ? 1 :nodeFlow.getExamineGrade();
        Integer abandonReasonNum = productOrder.getAbandonReasonNum()+1;
        Integer status=0;
//        有下一审核人
        if (examineGrade > abandonReasonNum) {
            status=0;
        }else {
            status=1;
        }
        return status;
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO APP接收老数据兼容接口（点击接收时调用）
     * @Date 13:24 2019/4/24
     * @Param
     **/
    public Map appAccecpt(String scOrderId,String userLoginName) {
        ValidateUtils.strNotEmpty(scOrderId, ProductOrderExcption.class, "生产订单id为空");
        Integer oldVerify = this.verifyOld(scOrderId);
        if (null!=oldVerify && oldVerify.equals(0)) {
            List ids = new ArrayList(){{
                add(scOrderId);
            }};
            String idsStr = ids.toString();
            this.receiveOrder(idsStr,userLoginName);
            return new HashMap(2){{
                put("receiveCode", 0);
                put("message","接收成功,当前订单已进入办理中");
            }};
        } else if (null != oldVerify && oldVerify.equals(1)) {
            return new HashMap(2){{
                put("receiveCode", 1);
                put("message","新流程可更改产品");
            }};
        }else {
            throw new ProductOrderExcption("流程节点信息异常");
        }
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 事业部订单查询service
     * @Date 18:20 2019/5/13
     * @Param
     **/
    public List<ProductOrder> orgOrderList(Map params) {
        UserEntity userEntity = sessionManager.getCurrentUser();// 当前操作人
        Map busDep = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
        ValidateUtils.strNotEmpty(busDep, CommonExcption.class, "未查询到当前登录人所属事业部");
        Long orgId = Long.parseLong(busDep.get("id").toString());
        ValidateUtils.strNotEmpty(orgId, CommonExcption.class,"部门id不可为空");
        params.put("orgId",orgId);
        searchUtils.paramsOperate(params);
        dataPermissionUtils.productOrgDataAccess(params, ModuleCodeConstant.RZSC_BUSDEPORDER_CODE);
        List<ProductOrder> orgOrderList = productOrderDao.getOrgOrderListWithPage(params);
        //翻译字段
        String[] transColum = {"originCode"};
        orgOrderList = translateUtil.translateList(transColum, orgOrderList);
        return orgOrderList;
    }

    /**
     * @Author Quanlin Wan
     * @Description //TODO 跨事业部转单service
     * @Date 19:01 2019/5/13
     * @Param
     * @return
     **/

    public void transferOrgOrderPage(Long orderId, Model model) {
        ValidateUtils.strNotEmpty(orderId, CommonExcption.class, "销售订单id不能为空");
        List<ProductOrder> orderList = productOrderDao.getListByOrderId(orderId,null,null);
        orderList = desUtil.decryptList(new String[]{"customerPhone"},orderList);//解密电话号码
        orderList = CustomerNumberEncryptionUtil.encryptionList(new String[]{"customerPhone"},orderList);//隐藏电话号码
        orderList = translateUtil.translateList(new String[]{"originCode","status"},orderList);
        model.addAttribute("orderList",orderList);
        StringBuffer productNames = new StringBuffer();
        for (int i = 0; i < orderList.size(); i++) {
            productNames.append(orderList.get(i).getProductName());
            if (i != orderList.size() - 1) {
                productNames.append("+");
            }
        }
        model.addAttribute("productNames",productNames);
    }


    public void afterSaleStatus(AfterSaleChangeStatusMessageVo vo) {
        if(StringUtils.isEmptyObj(vo)){
            throw new ProductOrderExcption("参数为空！");
        }
        List<AfterSaleChangeStatusProductItemVo> productList = vo.getProductList();
        for(AfterSaleChangeStatusProductItemVo itemVo : productList){
            if(StringUtils.isEmpty(itemVo.getScOrderId())){
                continue;
            }
            ProductOrder productOrder = productOrderDao.getMainOrderByScOrderId(itemVo.getScOrderId());
            if(StringUtils.isEmptyObj(productOrder)){
                continue;
            }
            ProductOrder updateProductOrder = new ProductOrder();
            updateProductOrder.setId(productOrder.getId());
            updateProductOrder.setAfterSaleNo(vo.getAfterSaleNo());
            updateProductOrder.setAfterSaleStatus(vo.getStatus());
            updateProductOrder.setUpdateTime(new Date());
            updateProductOrder.setUpdaterName("售后状态修改");
            productOrderDao.updateAfterSaleStatus(updateProductOrder);
        }
    }

    public void afterSaleProHandle(AfterSaleProductHandleMessageVo vo) {
        if(StringUtils.isEmptyObj(vo)){
            throw new ProductOrderExcption("参数为空！");
        }
        List<AfterSaleProductHandleItemVo> productList = vo.getProductHandleList();
        for(AfterSaleProductHandleItemVo itemVo : productList){
            if(org.apache.commons.lang3.StringUtils.isEmpty(itemVo.getScOrderId())){
                continue;
            }
            ProductOrder productOrder = productOrderDao.getMainOrderByScOrderId(itemVo.getScOrderId());
            if(StringUtils.isEmptyObj(productOrder)){
                continue;
            }
            ProductOrder updateProductOrder = new ProductOrder();
            updateProductOrder.setId(productOrder.getId());
            updateProductOrder.setProductHandleResultType(itemVo.getProductHandleResultType());
            updateProductOrder.setUpdateTime(new Date());
            updateProductOrder.setUpdaterName("售后处理结果修改");
            productOrderDao.updateAfterSaleStatus(updateProductOrder);
        }
    }

    public void updateCustomerName(Map param) {
        if(param.isEmpty()){
            throw new ProductOrderExcption("参数为空！");
        }
        String customerId = param.get("customerId").toString();
        String customerName = param.get("customerName").toString();
        if(StringUtils.isEmpty(customerId)){
            throw new ProductOrderExcption("客户ID为空！");
        }
        if(StringUtils.isEmpty(customerName)){
            throw new ProductOrderExcption("客户名称为空！");
        }
        productOrderDao.updateCustomerName(customerId,customerName);
    }
    public List<ProductOrder> selectByOrderIds(List<Long> ids){
        return productOrderDao.queryByOrderIds(ids);
    }
}
